<html>
<head>
</head>
<body style="background: transparent;">
    <script src="scripts/docstrap.lib.js"></script>
    <script src="scripts/lunr.min.js"></script>
    <script src="scripts/fulltext-search.js"></script>

    <script type="text/x-docstrap-searchdb">
    {"map_ContextMenu.js.html":{"id":"map_ContextMenu.js.html","title":"Source: map/ContextMenu.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/ContextMenu.js /*! * ol-contextmenu - v3.1.0 * Custom Context Menu for Openlayers * https://github.com/jonataswalker/ol-contextmenu * Built: Sat Nov 18 2017 09:49:39 GMT-0200 (-02) */ (function (global, factory) { typeof exports === 'object' &amp;&amp; typeof module !== 'undefined' ? module.exports = factory(require('openlayers')) : typeof define === 'function' &amp;&amp; define.amd ? define(['openlayers'], factory) : (global.ContextMenu = factory(global.ol)); }(this, (function (ol) { ol = ol &amp;&amp; ol.hasOwnProperty('default') ? ol['default'] : ol; var namespace = &quot;ol-ctx-menu&quot;; var container_class = &quot;-container&quot;; var separator_class = &quot;-separator&quot;; var submenu_class = &quot;-submenu&quot;; var hidden_class = &quot;-hidden&quot;; var icon_class = &quot;-icon&quot;; var zoom_in_class = &quot;-zoom-in&quot;; var zoom_out_class = &quot;-zoom-out&quot;; var ol_unselectable_class = &quot;ol-unselectable&quot;; var vars = { namespace: namespace, container_class: container_class, separator_class: separator_class, submenu_class: submenu_class, hidden_class: hidden_class, icon_class: icon_class, zoom_in_class: zoom_in_class, zoom_out_class: zoom_out_class, ol_unselectable_class: ol_unselectable_class }; var _VARS_ = Object.freeze({ namespace: namespace, container_class: container_class, separator_class: separator_class, submenu_class: submenu_class, hidden_class: hidden_class, icon_class: icon_class, zoom_in_class: zoom_in_class, zoom_out_class: zoom_out_class, ol_unselectable_class: ol_unselectable_class, default: vars }); const VARS = _VARS_; const EVENT_TYPE = { /** * Triggered before context menu is openned. */ BEFOREOPEN: 'beforeopen', /** * Triggered when context menu is openned. */ OPEN: 'open', /** * Triggered when context menu is closed. */ CLOSE: 'close', /** * Internal. Triggered when a menu entry is added. */ ADD_MENU_ENTRY: 'add-menu-entry', /** * Internal. */ CONTEXTMENU: 'contextmenu', /** * Internal. */ HOVER: 'mouseover' }; /** * DOM Elements classname */ const CLASSNAME = { container : VARS.namespace + VARS.container_class, separator : VARS.namespace + VARS.separator_class, submenu : VARS.namespace + VARS.submenu_class, hidden : VARS.namespace + VARS.hidden_class, icon : VARS.namespace + VARS.icon_class, zoomIn : VARS.namespace + VARS.zoom_in_class, zoomOut : VARS.namespace + VARS.zoom_out_class, OL_unselectable : VARS.ol_unselectable_class }; const DEFAULT_OPTIONS = { width: 150, scrollAt: 4, eventType: EVENT_TYPE.CONTEXTMENU, defaultItems: true }; const DEFAULT_ITEMS = [ { text: 'Zoom In', classname: ((CLASSNAME.zoomIn) + &quot; &quot; + (CLASSNAME.icon)), callback: function (obj, map) { const view = map.getView(); view.animate({ zoom: +view.getZoom() + 1, duration: 700, center: obj.coordinate }); } }, { text: 'Zoom Out', classname: ((CLASSNAME.zoomOut) + &quot; &quot; + (CLASSNAME.icon)), callback: function (obj, map) { const view = map.getView(); view.animate({ zoom: +view.getZoom() - 1, duration: 700, center: obj.coordinate }); } } ]; /** * Overwrites obj1's values with obj2's and adds * obj2's if non existent in obj1 * @returns obj3 a new object based on obj1 and obj2 */ function mergeOptions(obj1, obj2) { let obj3 = {}; for (let attr1 in obj1) { obj3[attr1] = obj1[attr1]; } for (let attr2 in obj2) { obj3[attr2] = obj2[attr2]; } return obj3; } function assert(condition, message) { if ( message === void 0 ) message = 'Assertion failed'; if (!condition) { if (typeof Error !== 'undefined') { throw new Error(message); } throw message; // Fallback } } /** * Does str contain test? * @param {String} str_test * @param {String} str * @returns Boolean */ function contains(str_test, str) { return !!~str.indexOf(str_test); } function getUniqueId() { return '_' + Math.random().toString(36).substr(2, 9); } function isDefAndNotNull(val) { // Note that undefined == null. return val != null; // eslint-disable-line no-eq-null } function isNumeric(str) { return /^\\d+$/.test(str); } /** * @param {Element|Array&lt;Element&gt;} element DOM node or array of nodes. * @param {String|Array&lt;String&gt;} classname Class or array of classes. * For example: 'class1 class2' or ['class1', 'class2'] * @param {Number|undefined} timeout Timeout to remove a class. */ function addClass(element, classname, timeout) { if (Array.isArray(element)) { element.forEach(function (each) { return addClass(each, classname); }); return; } const array = (Array.isArray(classname)) ? classname : classname.split(/\\s+/); let i = array.length; while (i--) { if (!hasClass(element, array[i])) { _addClass(element, array[i], timeout); } } } /** * @param {Element|Array&lt;Element&gt;} element DOM node or array of nodes. * @param {String|Array&lt;String&gt;} classname Class or array of classes. * For example: 'class1 class2' or ['class1', 'class2'] * @param {Number|undefined} timeout Timeout to add a class. */ function removeClass(element, classname, timeout) { if (Array.isArray(element)) { element.forEach(function (each) { return removeClass(each, classname, timeout); }); return; } const array = (Array.isArray(classname)) ? classname : classname.split(/\\s+/); let i = array.length; while (i--) { if (hasClass(element, array[i])) { _removeClass(element, array[i], timeout); } } } /** * @param {Element} element DOM node. * @param {String} classname Classname. * @return {Boolean} */ function hasClass(element, c) { // use native if available return element.classList ? element.classList.contains(c) : classRegex(c).test(element.className); } /** * @param {Element|Array&lt;Element&gt;} element DOM node or array of nodes. * @param {String} classname Classe. */ /** * Abstraction to querySelectorAll for increased * performance and greater usability * @param {String} selector * @param {Element} context (optional) * @param {Boolean} find_all (optional) * @return (find_all) {Element} : {Array} */ function find(selector, context, find_all) { if ( context === void 0 ) context = window.document; let simpleRe = /^(#?[\\w-]+|\\.[\\w-.]+)$/, periodRe = /\\./g, slice = Array.prototype.slice, matches = []; // Redirect call to the more performant function // if it's a simple selector and return an array // for easier usage if (simpleRe.test(selector)) { switch (selector[0]) { case '#': matches = [$(selector.substr(1))]; break; case '.': matches = slice.call(context.getElementsByClassName( selector.substr(1).replace(periodRe, ' '))); break; default: matches = slice.call(context.getElementsByTagName(selector)); } } else { // If not a simple selector, query the DOM as usual // and return an array for easier usage matches = slice.call(context.querySelectorAll(selector)); } return (find_all) ? matches : matches[0]; } function $(id) { id = (id[0] === '#') ? id.substr(1, id.length) : id; return document.getElementById(id); } function offset(element) { const rect = element.getBoundingClientRect(); const docEl = document.documentElement; return { left: rect.left + window.pageXOffset - docEl.clientLeft, top: rect.top + window.pageYOffset - docEl.clientTop, width: element.offsetWidth, height: element.offsetHeight }; } function getViewportSize() { return { w: window.innerWidth || document.documentElement.clientWidth, h: window.innerHeight || document.documentElement.clientHeight }; } function createFragment(html) { let frag = document.createDocumentFragment(), temp = document.createElement('div'); temp.innerHTML = html; while (temp.firstChild) { frag.appendChild(temp.firstChild); } return frag; } function classRegex(classname) { return new RegExp((&quot;(^|\\\\s+) &quot; + classname + &quot; (\\\\s+|$)&quot;)); } function _addClass(el, klass, timeout) { // use native if available if (el.classList) { el.classList.add(klass); } else { el.className = (el.className + ' ' + klass).trim(); } if (timeout &amp;&amp; isNumeric(timeout)) { window.setTimeout(function () { return _removeClass(el, klass); }, timeout); } } function _removeClass(el, klass, timeout) { if (el.classList) { el.classList.remove(klass); } else { el.className = (el.className.replace(classRegex(klass), ' ')).trim(); } if (timeout &amp;&amp; isNumeric(timeout)) { window.setTimeout(function () { return _addClass(el, klass); }, timeout); } } /** * @class Internal */ var Internal = function Internal(base) { /** * @type {ol.control.Control} */ this.Base = base; /** * @type {ol.Map} */ this.map = undefined; /** * @type {Element} */ this.viewport = undefined; /** * @type {ol.Coordinate} */ this.coordinateClicked = undefined; /** * @type {ol.Pixel} */ this.pixelClicked = undefined; /** * @type {Number} */ this.lineHeight = 0; /** * @type {Object} */ this.items = {}; /** * @type {Boolean} */ this.opened = false; /** * @type {Object} */ this.submenu = { left: base.options.width - 15 + 'px', lastLeft: '' // string + px }; /** * @type {Function} */ this.eventHandler = this.handleEvent.bind(this); return this; }; Internal.prototype.init = function init (map) { this.map = map; this.viewport = map.getViewport(); this.setListeners(); this.Base.Html.createMenu(); this.lineHeight = this.getItemsLength() &gt; 0 ? this.Base.container.offsetHeight / this.getItemsLength() : this.Base.Html.cloneAndGetLineHeight(); }; Internal.prototype.getItemsLength = function getItemsLength () { var this$1 = this; let count = 0; Object.keys(this.items).forEach(function (k) { if (this$1.items[k].submenu || this$1.items[k].separator) { return; } count++; }); return count; }; Internal.prototype.getPixelClicked = function getPixelClicked () { return this.pixelClicked; }; Internal.prototype.getCoordinateClicked = function getCoordinateClicked () { return this.coordinateClicked; }; Internal.prototype.positionContainer = function positionContainer (pixel) { var this$1 = this; const container = this.Base.container; const mapSize = this.map.getSize(); // how much (width) space left over const space_left_h = mapSize[1] - pixel[1]; // how much (height) space left over const space_left_w = mapSize[0] - pixel[0]; const menuSize = { w: container.offsetWidth, // a cheap way to recalculate container height // since offsetHeight is like cached h: Math.round(this.lineHeight * this.getItemsLength()) }; // submenus const subs = find((&quot;li.&quot; + (CLASSNAME.submenu) + &quot;&gt;div&quot;), container, true); if (space_left_w &gt;= menuSize.w) { container.style.right = 'auto'; container.style.left = (pixel[0] + 5) + &quot;px&quot;; } else { container.style.left = 'auto'; container.style.right = '15px'; } // set top or bottom if (space_left_h &gt;= menuSize.h) { container.style.bottom = 'auto'; container.style.top = (pixel[1] - 10) + &quot;px&quot;; } else { container.style.top = 'auto'; container.style.bottom = 0; } removeClass(container, CLASSNAME.hidden); if (subs.length) { if (space_left_w &lt; (menuSize.w * 2)) { // no space (at right) for submenu // position them at left this.submenu.lastLeft = &quot;-&quot; + (menuSize.w) + &quot;px&quot;; } else { this.submenu.lastLeft = this.submenu.left; } subs.forEach(function (sub) { // is there enough space for submenu height? const viewport = getViewportSize(); const sub_offset = offset(sub); const sub_height = sub_offset.height; let sub_top = space_left_h - sub_height; if (sub_top &lt; 0) { sub_top = sub_height - (viewport.h - sub_offset.top); sub.style.top = &quot;-&quot; + sub_top + &quot;px&quot;; } sub.style.left = this$1.submenu.lastLeft; }); } }; Internal.prototype.openMenu = function openMenu (pixel, coordinate) { this.Base.dispatchEvent({ type: EVENT_TYPE.OPEN, pixel: pixel, coordinate: coordinate }); this.opened = true; this.positionContainer(pixel); }; Internal.prototype.closeMenu = function closeMenu () { this.opened = false; addClass(this.Base.container, CLASSNAME.hidden); this.Base.dispatchEvent({ type: EVENT_TYPE.CLOSE }); }; Internal.prototype.setListeners = function setListeners () { this.viewport.addEventListener( this.Base.options.eventType, this.eventHandler, false); }; Internal.prototype.removeListeners = function removeListeners () { this.viewport.removeEventListener( this.Base.options.eventType, this.eventHandler, false); }; Internal.prototype.handleEvent = function handleEvent (evt) { const this_ = this; this.coordinateClicked = this.map.getEventCoordinate(evt); this.pixelClicked = this.map.getEventPixel(evt); this.Base.dispatchEvent({ type: EVENT_TYPE.BEFOREOPEN, pixel: this.pixelClicked, coordinate: this.coordinateClicked }); if (this.Base.disabled) { return; } if (this.Base.options.eventType === EVENT_TYPE.CONTEXTMENU) { // don't be intrusive with other event types evt.stopPropagation(); evt.preventDefault(); } this.openMenu(this.pixelClicked, this.coordinateClicked); //one-time fire evt.target.addEventListener('mousedown', { handleEvent: function (e) { this_.closeMenu(); evt.target.removeEventListener(e.type, this, false); } }, false); }; Internal.prototype.setItemListener = function setItemListener (li, index) { const this_ = this; if (li &amp;&amp; typeof this.items[index].callback === 'function') { (function (callback) { li.addEventListener('click', function (evt) { evt.preventDefault(); const obj = { coordinate: this_.getCoordinateClicked(), data: this_.items[index].data || null }; this_.closeMenu(); callback(obj, this_.map); }, false); })(this.items[index].callback); } }; /** * @class Html */ var Html = function Html(base) { this.Base = base; this.Base.container = this.container = this.createContainer(); return this; }; Html.prototype.createContainer = function createContainer (hidden) { const container = document.createElement('div'); const ul = document.createElement('ul'); const klasses =[CLASSNAME.container, CLASSNAME.OL_unselectable]; hidden &amp;&amp; klasses.push(CLASSNAME.hidden); container.className = klasses.join(' '); container.style.width = parseInt(this.Base.options.width, 10) + 'px'; container.appendChild(ul); return container; }; Html.prototype.createMenu = function createMenu () { let items = []; if ('items' in this.Base.options) { items = this.Base.options.defaultItems ? this.Base.options.items.concat(DEFAULT_ITEMS) : this.Base.options.items; } else if (this.Base.options.defaultItems) { items = DEFAULT_ITEMS; } // no item if (items.length === 0) { return false; } // create entries items.forEach(this.addMenuEntry, this); }; Html.prototype.addMenuEntry = function addMenuEntry (item) { var this$1 = this; if (item.items &amp;&amp; Array.isArray(item.items)) { // submenu - only a second level item.classname = item.classname || ''; if (!contains(CLASSNAME.submenu, item.classname)) { item.classname = item.classname.length ? ' ' + CLASSNAME.submenu : CLASSNAME.submenu; } let li = this.generateHtmlAndPublish(this.container, item); let sub = this.createContainer(); sub.style.left = this.Base.Internal.submenu.lastLeft || this.Base.Internal.submenu.left; li.appendChild(sub); item.items.forEach(function (each) { this$1.generateHtmlAndPublish(sub, each, true); }); } else { this.generateHtmlAndPublish(this.container, item); } }; Html.prototype.generateHtmlAndPublish = function generateHtmlAndPublish (parent, item, submenu) { let html, frag, element, separator = false; const index = getUniqueId(); // separator if (typeof item === 'string' &amp;&amp; item.trim() === '-') { html = [ '&lt;li id=&quot;', index, '&quot; class=&quot;', CLASSNAME.separator, '&quot;&gt;', '&lt;hr&gt;&lt;/li&gt;' ].join(''); frag = createFragment(html); // http://stackoverflow.com/a/13347298/4640499 element = [].slice.call(frag.childNodes, 0)[0]; parent.firstChild.appendChild(frag); // to exclude from lineHeight calculation separator = true; } else { item.classname = item.classname || ''; html = '&lt;span&gt;' + item.text + '&lt;/span&gt;'; frag = createFragment(html); element = document.createElement('li'); if (item.icon) { if (item.classname === '') { item.classname = CLASSNAME.icon; } else if (item.classname.indexOf(CLASSNAME.icon) === -1) { item.classname += ' ' + CLASSNAME.icon; } element.setAttribute('style', (&quot;background-image:url(&quot; + (item.icon) + &quot;)&quot;)); } element.id = index; element.className = item.classname; element.appendChild(frag); parent.firstChild.appendChild(element); } this.Base.Internal.items[index] = { id: index, submenu: submenu || 0, separator: separator, callback: item.callback, data: item.data || null }; this.Base.Internal.setItemListener(element, index); return element; }; Html.prototype.removeMenuEntry = function removeMenuEntry (index) { const element = find('#' + index, this.container.firstChild); element &amp;&amp; this.container.firstChild.removeChild(element); delete this.Base.Internal.items[index]; }; Html.prototype.cloneAndGetLineHeight = function cloneAndGetLineHeight () { // for some reason I have to calculate with 2 items const cloned = this.container.cloneNode(); const frag = createFragment('&lt;span&gt;Foo&lt;/span&gt;'); const frag2 = createFragment('&lt;span&gt;Foo&lt;/span&gt;'); const element = document.createElement('li'); const element2 = document.createElement('li'); element.appendChild(frag); element2.appendChild(frag2); cloned.appendChild(element); cloned.appendChild(element2); this.container.parentNode.appendChild(cloned); const height = cloned.offsetHeight / 2; this.container.parentNode.removeChild(cloned); return height; }; /** * @class Base * @extends {ol.control.Control} */ var Base = (function (superclass) { function Base(opt_options) { if ( opt_options === void 0 ) opt_options = {}; assert( typeof opt_options == 'object', '@param `opt_options` should be object type!' ); this.options = mergeOptions(DEFAULT_OPTIONS, opt_options); this.disabled = false; this.Internal = new Internal(this); this.Html = new Html(this); superclass.call(this, { element: this.container }); } if ( superclass ) Base.__proto__ = superclass; Base.prototype = Object.create( superclass &amp;&amp; superclass.prototype ); Base.prototype.constructor = Base; /** * Remove all elements from the menu. */ Base.prototype.clear = function clear () { Object.keys(this.Internal.items) .forEach(this.Html.removeMenuEntry, this.Html); }; /** * Close the menu programmatically. */ Base.prototype.close = function close () { this.Internal.closeMenu(); }; /** * Enable menu */ Base.prototype.enable = function enable () { this.disabled = false; }; /** * Disable menu */ Base.prototype.disable = function disable () { this.disabled = true; }; /** * @return {Array} Returns default items */ Base.prototype.getDefaultItems = function getDefaultItems () { return DEFAULT_ITEMS; }; /** * @return {Number} Returns how many items */ Base.prototype.countItems = function countItems () { return Object.keys(this.Internal.items).length; }; /** * Add items to the menu. This pushes each item in the provided array * to the end of the menu. * @param {Array} arr Array. */ Base.prototype.extend = function extend (arr) { assert(Array.isArray(arr), '@param `arr` should be an Array.'); arr.forEach(this.push, this); }; Base.prototype.isOpen = function isOpen () { return this.Internal.opened; }; /** * Update the menu's position. */ Base.prototype.updatePosition = function updatePosition (pixel) { assert(Array.isArray(pixel), '@param `pixel` should be an Array.'); if (this.isOpen()) { this.Internal.positionContainer(pixel); } }; /** * Remove the last item of the menu. */ Base.prototype.pop = function pop () { const keys = Object.keys(this.Internal.items); this.Html.removeMenuEntry(keys[keys.length - 1]); }; /** * Insert the provided item at the end of the menu. * @param {Object|String} item Item. */ Base.prototype.push = function push (item) { assert(isDefAndNotNull(item), '@param `item` must be informed.'); this.Html.addMenuEntry(item); }; /** * Remove the first item of the menu. */ Base.prototype.shift = function shift () { this.Html.removeMenuEntry(Object.keys(this.Internal.items)[0]); }; /** * Not supposed to be used on app. */ Base.prototype.setMap = function setMap (map) { ol.control.Control.prototype.setMap.call(this, map); if (map) { // let's start since now we have the map this.Internal.init(map, this); } else { // I'm removed from the map - remove listeners this.Internal.removeListeners(); } }; return Base; }(ol.control.Control)); return Base; }))); × Search results Close "},"map_Controls.js.html":{"id":"map_Controls.js.html","title":"Source: map/Controls.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/Controls.js import { ol } from '../constants' import * as utils from '../utils/utils' import '../control/BZoomSlider' import '../control/FullScreen' import '../control/zoom' import '../control/compareLayer' import '../control/contextMenu' import '../control/LayerSwitcher' import '../control/Loading' import '../control/MousePosition' import '../control/OverviewMap' import '../control/RotateControl' import '../control/ScaleLineH' class _Controls { /** * 添加控件 * @param params * @returns {Array} * @private */ _addControls (params) { let options = params || {} let controls = [] // 添加缩放 if (!options.hasOwnProperty('zoom')) { this.addZoom({}, controls) } // 添加旋转 if (!options.hasOwnProperty('rotate')) { this.addRotate({}, controls) } // 添加版权 if (!options.hasOwnProperty('attribution')) { this.addAttribution({}, controls) } if (options) { for (let key in options) { if (key &amp;&amp; options[key]) { this['add' + (utils.upperFirstChart(key))](options[key], controls) } } } return controls } /** * 添加缩放按钮 * @param options * @param controls * @private */ addZoom(options = {}, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.ZoomMenu({ className: options['className'], duration: options['duration'], target: options['target'], delta: options['delta'] })) } /** * 添加旋转控件 * @param options * @param controls * @private */ addRotate(options = {}, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.RotateControl({ className: options['className'], duration: options['duration'], label: options['resetNorth'], autoHide: options['autoHide'], target: options['target'] })) } /** * 版权 * @param options * @param controls * @private */ addAttribution(options, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.Attribution({ className: (options['className'] ? options['className'] : 'ol-attribution'), label: (options['label'] ? options['label'] : 'i'), tipLabel: (options['tipLabel'] &amp;&amp; typeof options['tipLabel'] === 'string' ? options['tipLabel'] : '版权'), collapsible: (options['collapsible'] === false ? options['collapsible'] : true), collapsed: (options['collapsed'] === false ? options['collapsed'] : true), collapseLabel: (options['collapseLabel'] ? options['collapseLabel'] : '»'), target: (options['target'] ? options['target'] : undefined) })) } /** * 添加比例尺 * @param options * @param controls * @private */ addScaleLine(options, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.ScaleLineH({ units: (options['units'] ? options['units'] : 'metric_cn') })) } /** * 添加全屏控件 * @param options * @param controls */ addFullScreen(options = {}, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.FullScreenMenu({ className: options['className'], label: options['label'], labelActive: options['labelActive'], keys: options['keys'], target: options['target'], source: options['source'] })) } /** * 添加鼠标位置控件 * @param options * @param controls */ addMousePosition(options = {}, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.MousePosition({ className: (options['className'] ? options['className'] : 'ol-mouse-position'), coordinateFormat: (options['coordinateFormat'] ? options['coordinateFormat'] : undefined), projection: (options['projection'] ? options['projection'] : this.view.getProjection()), undefinedHTML: (options['undefinedHTML'] &amp;&amp; typeof options['undefinedHTML'] === 'string' ? options['undefinedHTML'] : '无坐标'), target: (options['target'] ? options['target'] : undefined) })) } /** * 添加缩放条控件 * @param options * @param controls */ addZoomSlider(options, controls) { controls = controls || this.map.getControls() let zoomSlider = new ol.control.BZoomSlider({ duration: options['duration'], pixelDelta: options['pixelDelta'], className: options['className'], target: options['target'] }) controls.push(zoomSlider) } /** * 添加缩放范围控件 * @param options * @param controls */ addZoomToExtent(options, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.ZoomToExtent({ className: (options['className'] ? options['className'] : 'ol-zoom-extent'), label: (options['label'] ? options['label'] : 'E'), tipLabel: (options['tipLabel'] &amp;&amp; typeof options['tipLabel'] === 'string' ? options['tipLabel'] : '缩放到范围'), extent: (options['extent'] ? options['extent'] : undefined) })) } /** * 添加定位控件 * @param options * @param controls * @private */ addGeolocation(options, controls) { controls = controls || this.map.getControls() controls.push(new ol.control.Geolocation({ className: (options['className'] ? options['className'] : 'gmap-geolocation'), target: (options['target'] ? options['target'] : undefined) })) } /** * 添加loading控件 * @param options * @param controls * @private */ addLoading(options, controls) { controls = controls || this.map.getControls() let loading_ = new ol.control.Loading({ className: (options['className'] ? options['className'] : 'gmap-loading-panel'), widget: (options['widget'] ? options['widget'] : 'animatedGif'), target: (options['target'] ? options['target'] : undefined) }) controls.push(loading_) } /** * 添加CompareLayer控件 * @param beforeMap * @param afterMap * @param options * @param controls * @private */ addCompareLayer(beforeMap, afterMap, options = {}, controls) { controls = controls || this.map.getControls() let _compareLayer = new ol.control.CompareLayer(beforeMap, afterMap, options) controls.push(_compareLayer) } /** * 添加ContextMenu控件 * @param options * @param controls * @private */ addContextMenu(options = {}, controls) { controls = controls || this.map.getControls() let ContextMenu = new ol.control.ContextMenu(options) controls.push(ContextMenu) } /** * 添加LayerSwitcher控件 * @param options * @param controls * @private */ addLayerSwitcher(options = {}, controls) { controls = controls || this.map.getControls() let Switcher = new ol.control.LayerSwitcher(options) controls.push(Switcher) } } export default _Controls × Search results Close "},"map_View.js.html":{"id":"map_View.js.html","title":"Source: map/View.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/View.js import { ol } from '../constants' class _View { /** * 添加视图 * @param params * @returns {ol.View} * @private */ _addView (params) { let option = params || {} /** * 投影 * @type {ol.proj.Projection} */ this.projection = ol.proj.get((option['projection'] || 'EPSG:3857')) /** * 显示范围 * @type {Array} */ this.fullExtent = option['extent'] /** * 投影范围 */ if (this.fullExtent) { this.projection.setExtent(this.fullExtent) } return new ol.View({ center: ((option['center'] &amp;&amp; Array.isArray(option['center'])) ? option['center'] : [0, 0]), zoom: ((option['zoom'] &amp;&amp; (typeof option['zoom'] === 'number')) ? option['zoom'] : 0), minZoom: ((option['minZoom'] &amp;&amp; (typeof option['minZoom'] === 'number')) ? option['minZoom'] : undefined), maxZoom: ((option['maxZoom'] &amp;&amp; (typeof option['maxZoom'] === 'number')) ? option['maxZoom'] : undefined), zoomFactor: ((option['zoomFactor'] &amp;&amp; (typeof option['zoomFactor'] === 'number')) ? option['zoomFactor'] : 2), rotation: ((option['rotation'] &amp;&amp; (typeof option['rotation'] === 'number')) ? option['rotation'] : 0), enableRotation: (option['enableRotation'] === false ? option['enableRotation'] : true), projection: (option['projection'] ? option['projection'] : 'EPSG:3857'), extent: ((option['extent'] &amp;&amp; Array.isArray(option['extent']) &amp;&amp; option['extent'].length === 4) ? option['extent'] : undefined), resolutions: ((option['resolutions'] &amp;&amp; Array.isArray(option['resolutions']) &amp;&amp; option['resolutions'].length &gt; 0) ? option['resolutions'] : undefined) }) } /** * 放大 */ zoomIn (duration) { let zoom = this.map.getView().getZoom() this.map.getView().animate({ zoom: (zoom + 1), duration: ((duration &amp;&amp; typeof duration === 'number') ? duration : 300) }) } /** * 缩小 */ zoomOut (duration) { let zoom = this.map.getView().getZoom() this.map.getView().animate({ zoom: (zoom - 1), duration: ((duration &amp;&amp; typeof duration === 'number') ? duration : 300) }) } /** * zoomByDelta * @param delta * @param duration * @returns {boolean} */ zoomByDelta (delta, duration) { let view = this.map.getView() if (!view || !(view instanceof ol.View)) { return false } else { let currentResolution = view.getResolution() if (currentResolution) { let newResolution = view.constrainResolution(currentResolution, delta) if (duration &gt; 0) { if (view.getAnimating()) { view.cancelAnimations() } view.animate({ resolution: newResolution, duration: duration, easing: ol.easing.easeOut }) } else { view.setResolution(newResolution) } } } } zoomAtFeature (feature){ var view=this.map.getView(); view.animate({ center: this.getCenterPositonByFeature(feature), duration: 2000 }); } getCenterPositonByFeature(feature){ var geometry = feature.getGeometry(); var extent = geometry.getExtent(); var position = ol.proj.transform([(extent[0]+extent[2])/2, (extent[1]+extent[3])/2], 'EPSG:3857', 'EPSG:4326'); position = ol.proj.fromLonLat([position[0], position[1]]); return position; } } export default _View × Search results Close "},"utils_domUtils.js.html":{"id":"utils_domUtils.js.html","title":"Source: utils/domUtils.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: utils/domUtils.js import { splitWords } from './utils' /** * 通过id获取dom * @param id * @returns {Element} */ export const get = (id) =&gt; { return typeof id === 'string' ? document.getElementById(id) : id } /** * 获取父节点下指定的子节点 * @param str * @param container * @returns {NodeList|*} */ export const getChildByTagName = (str, container) =&gt; { return container.getElementsByTagName(str) } /** * 通过类名获取元素 * @param str * @param container * @param root * @returns {HTMLElement} */ export const getElementsByClassName = (str, container, root) =&gt; { let _root = root || window let $ = _root.document.querySelector.bind(_root.document) // let $$ = _root.document.querySelectorAll.bind(_root.document) let target = $(str) return target } /** * 获取dom class * @param elem * @returns {*|getAttribute|string|string} */ export const getClass = (elem) =&gt; { return elem.getAttribute &amp;&amp; elem.getAttribute('class') || '' } /** * 获取dom样式列表（） * @param el * @param style * @returns {*} */ export const getStyle = (el, style) =&gt; { let value = el.style[style] || (el.currentStyle &amp;&amp; el.currentStyle[style]) if ((!value || value === 'auto') &amp;&amp; document.defaultView) { let css = document.defaultView.getComputedStyle(el, null) value = css ? css[style] : null } return value === 'auto' ? null : value } /** * 创建dom * @param tagName (标签名) * @param className (类名) * @param container (容器) * @param id (唯一标识) * @returns {Element} */ export const create = (tagName, className, container, id) =&gt; { let el = document.createElement(tagName) el.className = className || '' if (id) { el.id = id } if (container) { container.appendChild(el) } return el } /** * 移除当前dom * @param el */ export const remove = (el) =&gt; { let parent = el.parentNode if (parent) { parent.removeChild(el) } } /** * 将dom致空 * @param el */ export const empty = (el) =&gt; { while (el.firstChild) { el.removeChild(el.firstChild) } } /** * 添加到容器前方 * @param el */ export const toFront = (el) =&gt; { el.parentNode.appendChild(el) } /** * 添加到容器后放 * @param el */ export const toBack = (el) =&gt; { let parent = el.parentNode parent.insertBefore(el, parent.firstChild) } /** * 判断DOM对象是否有此类名 * @param el * @param name * @returns {boolean} */ export const hasClass = (el, name) =&gt; { if (el.classList !== undefined) { return el.classList.contains(name) } let className = getClass(el) return className.length &gt; 0 &amp;&amp; new RegExp('(^|\\\\s)' + name + '(\\\\s|$)').test(className) } /** * 添加类名 * @param el * @param name */ export const addClass = (el, name) =&gt; { if (el.classList !== undefined) { let classes = splitWords(name) for (let i = 0, len = classes.length; i &lt; len; i++) { el.classList.add(classes[i]) } } else if (!hasClass(el, name)) { let className = getClass(el) setClass(el, (className ? className + ' ' : '') + name) } } /** * 移除类名 * @param el * @param name */ export const removeClass = (el, name) =&gt; { if (el.classList !== undefined) { el.classList.remove(name) } else { setClass(el, String.trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' '))) } } /** * 设置class * @param el * @param name */ export const setClass = (el, name) =&gt; { if (el.className.baseVal === undefined) { el.className = name } else { el.className.baseVal = name } } /** * 创建一个隐藏的元素 * @param tagName * @param parent * @param id * @returns {Element} */ export const createHidden = (tagName, parent, id) =&gt; { let element = document.createElement(tagName) element.style.display = 'none' if (id) { element.id = id } if (parent) { parent.appendChild(element) } return element } × Search results Close "},"event_Events.js.html":{"id":"event_Events.js.html","title":"Source: event/Events.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: event/Events.js import { stamp } from '../utils/utils' /** * 绑定事件 * @param listenerObj * @returns {boundListener} * @private */ export const bindListener = function (listenerObj) { let boundListener = function (evt) { let listener = listenerObj.listener let bindTo = listenerObj.bindTo || listenerObj.target if (listenerObj.callOnce) { unListenByKey(listenerObj) } return listener.call(bindTo, evt) } listenerObj.boundListener = boundListener return boundListener } /** * 查找监听器 * @param listeners * @param listener * @param optThis * @param optSetDeleteIndex * @returns {*} */ export const findListener = function (listeners, listener, optThis, optSetDeleteIndex) { let listenerObj = null for (let i = 0, ii = listeners.length; i &lt; ii; ++i) { listenerObj = listeners[i] if (listenerObj.listener === listener &amp;&amp; listenerObj.bindTo === optThis) { if (optSetDeleteIndex) { listenerObj.deleteIndex = i } return listenerObj } } return undefined } /** * get Listeners * @param target * @param type * @returns {undefined} */ export const getListeners = function (target, type) { let listenerMap = target.vlm return listenerMap ? listenerMap[type] : undefined } /** * Get the lookup of listeners. If one does not exist on the target, it is * @param target * @returns {{}|*} * @private */ export const getListenerMap = function (target) { let listenerMap = target.vlm if (!listenerMap) { listenerMap = target.vlm = {} } return listenerMap } /** * 清空事件 * @param target * @param type */ export const removeListeners = function (target, type) { let listeners = getListeners(target, type) if (listeners) { for (let i = 0, ii = listeners.length; i &lt; ii; ++i) { target.removeEventListener(type, listeners[i].boundListener) clear(listeners[i]) } listeners.length = 0 let listenerMap = target.vlm if (listenerMap) { delete listenerMap[type] if (Object.keys(listenerMap).length === 0) { delete target.vlm } } } } /** * 注册事件处理 * @param target * @param type * @param listener * @param optThis * @param optOnce * @returns {*} */ export const listen = function (target, type, listener, optThis, optOnce) { let listenerMap = getListenerMap(target) let listeners = listenerMap[type] if (!listeners) { listeners = listenerMap[type] = [] } let listenerObj = findListener(listeners, listener, optThis, false) if (listenerObj) { if (!optOnce) { listenerObj.callOnce = false } } else { listenerObj = ({ bindTo: optThis, callOnce: !!optOnce, listener: listener, target: target, type: type }) target.addEventListener(type, bindListener(listenerObj)) listeners.push(listenerObj) } return listenerObj } /** * 注册事件，只触发一次 * @param target * @param type * @param listener * @param optThis * @returns {*} */ export const listenOnce = function (target, type, listener, optThis) { return listen(target, type, listener, optThis, true) } /** * 取消事件注册 * @param target * @param type * @param listener * @param optThis */ export const unListen = function (target, type, listener, optThis) { let listeners = getListeners(target, type) if (listeners) { let listenerObj = findListener(listeners, listener, optThis, true) if (listenerObj) { unListenByKey(listenerObj) } } } /** * 根据事件名移除事件对象 * @param key */ export const unListenByKey = function (key) { if (key &amp;&amp; key.target) { key.target.removeEventListener(key.type, key.boundListener) let listeners = getListeners(key.target, key.type) if (listeners) { let i = 'deleteIndex' in key ? key.deleteIndex : listeners.indexOf(key) if (i !== -1) { listeners.splice(i, 1) } if (listeners.length === 0) { removeListeners(key.target, key.type) } } clear(key) } } /** * 清空当前对象 * @param object */ export const clear = function (object) { for (let property in object) { delete object[property] } } /** * 移除所有事件监听 * @param target */ export const unlistenAll = function (target) { let listenerMap = getListenerMap(target) for (let type in listenerMap) { removeListeners(target, type) } } /** * 获取事件唯一标识 * @param type * @param fn * @param context * @returns {string} */ export const getDomEventKey = (type, fn, context) =&gt; { return '_dom_event_' + type + '_' + stamp(fn) + (context ? '_' + stamp(context) : '') } /** * 对DOM对象添加事件监听 * @param element * @param type * @param fn * @param context * @returns {*} */ export const addListener = function (element, type, fn, context) { let eventKey = getDomEventKey(type, fn, context) let handler = element[eventKey] if (handler) { return this } handler = function (e) { return fn.call(context || element, e) } if ('addEventListener' in element) { element.addEventListener(type, handler, false) } else if ('attachEvent' in element) { element.attachEvent('on' + type, handler) } element[eventKey] = handler return this } /** * 移除DOM对象监听事件 * @param element * @param type * @param fn * @param context * @returns {removeListener} */ export const removeListener = function (element, type, fn, context) { let eventKey = getDomEventKey(type, fn, context) let handler = element[eventKey] if (!handler) { return this } if ('removeEventListener' in element) { element.removeEventListener(type, handler, false) } else if ('detachEvent' in element) { element.detachEvent('on' + type, handler) } element[eventKey] = null return this } × Search results Close "},"utils_utils.js.html":{"id":"utils_utils.js.html","title":"Source: utils/utils.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: utils/utils.js import { OL_Style_Type } from '../constants' /** * 获取两数值之间的随机值 * @param t1 &lt;下限&gt; * @param t2 &lt;上限&gt; * @param t3 &lt;需要保留的小数位, 不能大于十五位&gt; * @returns {*} */ export const getrandom = (t1, t2, t3) =&gt; { if (!t1 || isNaN(t1)) { t1 = 0 } if (!t2 || isNaN(t2)) { t2 = 1 } if (!t3 || isNaN(t3)) { t3 = 0 } t3 = t3 &gt; 15 ? 15 : t3 let [ra, du] = [(Math.random() * (t2 - t1) + t1), (Math.pow(10, t3))] ra = (Math.round(ra * du) / du) return ra } /** * 获取id * @returns {*|string|!Array.&lt;T&gt;} */ export const getuuid = () =&gt; { let [s, hexDigits] = [ [], '0123456789abcdef' ] for (let i = 0; i &lt; 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1) } s[14] = '4' s[19] = hexDigits.substr((s[19] &amp; 0x3) | 0x8, 1) s[8] = s[13] = s[18] = s[23] = '-' return (s.join('')) } /** * 添加标识 * @param obj * @returns {*} */ export const stamp = function(obj) { let key = '_event_id_' obj[key] = obj[key] || (getuuid()) return obj[key] } /** * 去除字符串前后空格 * @param str * @returns {*} */ export const trim = (str) =&gt; { return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '') } /** * 将类名截取成数组 * @param str * @returns {Array|*} */ export const splitWords = (str) =&gt; { return trim(str).split(/\\s+/) } /** * 首字母大写(其他小写) * @param str * @returns {string} */ export const firstUpperToCase = (str) =&gt; { return (str.toLowerCase().replace(/( |^)[a-z]/g, (L) =&gt; L.toUpperCase())) } /** * 只转换第一个字母 * @param str */ export const upperFirstChart = str =&gt; { return (str.replace(/( |^)[a-z]/g, (L) =&gt; L.toUpperCase())) } /** * arrayRemove * @param arr * @param obj * @returns {boolean} */ export const arrayRemove = (arr, obj) =&gt; { let i = arr.indexOf(obj) let found = i &gt; -1 if (found) { arr.splice(i, 1) } return found } /** * 判断是否为对象 * @param value * @returns {boolean} */ export const isObject = value =&gt; { const type = typeof value return value !== null &amp;&amp; (type === 'object' || type === 'function') } /** * 判断是否为字符串 * @param value * @returns {boolean} */ export const isString = value =&gt; { const type = typeof value return type === 'string' } // /** // * kljson 样式转换成ol格式 // * @param json // * @param prop // * @returns {object} // */ // export const json2obj = (json,prop) =&gt; { // if(!json) return null; // let obj=Object.assign({},json); // let clzz= OL_Style_Type[prop]; // if(!clzz){ // if(obj.xt){ // clzz=OL_Style_Type[obj.xt]; // if(!clzz) // clzz='ol.'+prop+'.'+this.upperFirstChart(obj.xt); // }else{ // clzz='ol.'+prop+'.'+this.upperFirstChart(prop); // } // } // for(var value in obj){ // if(typeof(value)=='object' &amp;&amp; !Array.isArray(value)){ // self[key]=this.json2obj(value,key); // } // } // return found // } × Search results Close "},"map_BaseLayers.js.html":{"id":"map_BaseLayers.js.html","title":"Source: map/BaseLayers.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/BaseLayers.js import { ol, layerConfigDefautls, projzh } from '../constants' const objectAssign = require('object-assign'); class BaseLayers { /** * 获取版权信息 * @returns {Xr.Attribution|Jr.Attribution|Wr.Attribution|*|ol.Attribution|ol.control.Attribution} * @private */ _getAttribution(params) { let attribution if (params === true) { params = {} params['url'] = config.INDEX_URL params['messages'] = 'contributors.' params['title'] = 'GMap' attribution = new ol.Attribution({ html: '&amp;copy; ' + '&lt;a href=&quot;' + params['url'] + '&quot;&gt;' + params['title'] + '&lt;/a&gt; ' + params['messages'] }) } else if (typeof params === 'object') { attribution = new ol.Attribution({ html: '&amp;copy; ' + '&lt;a href=&quot;' + params['url'] + '&quot;&gt;' + params['title'] + '&lt;/a&gt; ' + params['messages'] }) } return attribution } addBaseLayers(params) { let options = params || []; if (!options || !Array.isArray(options) || options.length &lt;= 0) { return [new ol.layer.Group({ layers: [this._getLayer({ layerName: 'AMap_online', layerType: 'AMap_online', tileType: 0, isVisible: true, isDefault: true, isBaseLayer: true, attribution: { url: 'http://www.keepsoft.net/', title: '贵仁科技', messages: '版权所有' } })], isBaseLayer: true })] } else { return [new ol.layer.Group({ layers: this._getBaseLayerGroup(params) })] } } /** * 获取图层组 * @returns {ol.layer.Group} */ _getBaseLayerGroup(layerConfig) { let layers = []; if (layerConfig &amp;&amp; Array.isArray(layerConfig) &amp;&amp; layerConfig.length &gt; 0) { layerConfig.forEach(config =&gt; { if (config['layerName'] &amp;&amp; config['layerType']) { let options = objectAssign({}, layerConfigDefautls, config); let layer = this._getLayer(options); if (layer) layers.push(layer); } }) } return layers; } /** * 获取图层 * @param layerConfig * @returns {*} * @private */ _getLayer(layerConfig) { let layer; switch (layerConfig['layerType']) { case 'AMap_online': layer = this._getAMapLayer_online(layerConfig) break; case 'TianDiMap_online': layer = this._getTianDiLayer_online(layerConfig) break; case 'BaiDu_online': layer = this._getBaiDuLayer_online(layerConfig) break; case 'GoogleMap_online': layer = this._getGoogleLayer_online(layerConfig) break; case 'AMap_offline': layer = this._getAMapLayer_offline(layerConfig) break; case 'GoogleMap_offline': layer = this._getGoogleLayer_offline(layerConfig) break; // case 'BaiDu_offline': // layer = this._getBaiDuLayer_offline(layerConfig) // break; case 'geojson': layer = this._getGeoJson(layerConfig); break; case 'kljson': layer = this._getKlJson(layerConfig); break; case 'wms': layer = this._getImageWMSLayer(layerConfig); break; case 'Arcgis_offline': layer = this._getArcGisLayer_offline(layerConfig); break; case 'ArcGis_server': layer = this._getAArcGis_server(layerConfig); break; default: throw new Error('不支持的图层类型！') } layer = this._addLayerAlias(layer, layerConfig) return layer; } /** * 添加底图标识 * @param layer * @param layerConfig * @returns {*} * @private */ _addLayerAlias(layer, layerConfig) { const isDefault = (layerConfig['isDefault'] === true) ? layerConfig['isDefault'] : false layer.set('isDefault', isDefault) layer.set('isBaseLayer', true) layer.setVisible(isDefault) layerConfig.viewonly &amp;&amp; layer.set('viewonly',true); layerConfig.hidden &amp;&amp; layer.setVisible(false); if (this.isHasAttribution === 0) { layer.getSource().setAttributions(this._getAttribution(layerConfig['attribution'])) this.isHasAttribution = 1 } return layer } /** * * 获取在线高德地图底图 * @param config * @returns {ol.layer.Tile} */ _getAMapLayer_online(options) { let url; switch (options['tileType']) { case 0: url = &quot;http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&amp;y={y}&amp;z={z}&amp;lang=zh_cn&amp;size=1&amp;scl=1&amp;style=7&quot;; break; case 1: url = &quot;http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&amp;y={y}&amp;z={z}&amp;lang=zh_cn&amp;size=1&amp;scl=2&amp;style=7&quot;; break; case 2: url = &quot;http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&amp;y={y}&amp;z={z}&amp;lang=zh_cn&amp;size=1&amp;scl=1&amp;style=6&quot;; break; case 3: url = &quot;http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&amp;y={y}&amp;z={z}&amp;lang=zh_cn&amp;size=1&amp;scl=1&amp;style=8&quot;; break; case 4: url = &quot;http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&amp;y={y}&amp;z={z}&amp;lang=zh_cn&amp;size=1&amp;scl=2&amp;style=8&quot;; break; } let _options = objectAssign({}, { source: new ol.source.XYZ({ projection: ol.proj.get('EPSG:3857'), wrapX: true, opaque: (options['opaque'] === true) ? true : false, // 图层是否不透明（主题相关） url: url, crossOrigin: 'Anonymous' }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * * 获取离线高德地图底图 * @param config * @returns {ol.layer.Tile} */ _getAMapLayer_offline(options) { let url; let _options = objectAssig({}, { source: new ol.source.XYZ({ url: options['url'] }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * *获取在线天地图底图 * @param {any} config * @memberof BaseLayers */ _getTianDiLayer_online(options) { let url; switch (options['tileType']) { case 0: url = &quot;http://t{0-4}.tianditu.com/DataServer?T=cva_w&amp;x={x}&amp;y={y}&amp;l={z}&quot;; break; case 1: url = &quot;http://t{0-4}.tianditu.com/DataServer?T=vec_w&amp;x={x}&amp;y={y}&amp;l={z}&quot;; break; case 2: url = &quot;http://t{0-4}.tianditu.com/DataServer?T=cia_w&amp;x={x}&amp;y={y}&amp;l={z}&quot;; break; case 3: url = &quot;http://t{0-4}.tianditu.com/DataServer?T=img_w&amp;x={x}&amp;y={y}&amp;l={z}&quot;; break; } let _options = objectAssign({}, { source: new ol.source.XYZ({ projection: ol.proj.get('EPSG:3857'), wrapX: true, opaque: (options['opaque'] === true) ? true : false, // 图层是否不透明（主题相关） url: url, crossOrigin: 'Anonymous', }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * * 获取在线百度地图 * @param {any} config * @memberof BaseLayers */ _getBaiDuLayer_online(options) { let extent = [72.004, 0.8293, 137.8347, 55.8271]; //定义百度坐标 //地址：https://github.com/openlayers/openlayers/issues/3522 let baiduMercator = new ol.proj.Projection({ code: 'baidu', extent: ol.extent.applyTransform(extent, projzh.ll2bmerc), units: 'm' }); ol.proj.addProjection(baiduMercator); ol.proj.addCoordinateTransforms('EPSG:4326', baiduMercator, projzh.ll2bmerc, projzh.bmerc2ll); ol.proj.addCoordinateTransforms('EPSG:3857', baiduMercator, projzh.smerc2bmerc, projzh.bmerc2smerc); let resolutions = []; for (let i = 0; i &lt; 19; i++) { resolutions[i] = Math.pow(2, 18 - i); } let tilegrid = new ol.tilegrid.TileGrid({ origin: [0, 0], resolutions: resolutions, extent: ol.extent.applyTransform(extent, projzh.ll2bmerc), tileSize: [256, 256] }); let satUrls = [0, 1, 2, 3, 4].map(function (sub) { return 'http://shangetu' + sub + '.map.bdimg.com/it/u=x={x};y={y};z={z};v=009;type=sate&amp;fm=46&amp;udt=20150601'; }); let urls = [0, 1, 2, 3, 4].map(function (sub) { return 'http://online' + sub + '.map.bdimg.com/onlinelabel/qt=tile&amp;x={x}&amp;y={y}&amp;z={z}&amp;v=009&amp;styles=pl&amp;udt=20170301&amp;scaler=1&amp;p=1'; }); let _options = objectAssign({}, { source: new ol.source.TileImage({ projection: 'baidu', tileGrid: tilegrid, tileUrlFunction: function (tileCoord, pixelRatio, proj) { if (!tileCoord) return &quot;&quot;; let z = tileCoord[0]; let x = tileCoord[1]; let y = tileCoord[2]; let hash = (x &lt;&lt; z) + y; let index = hash % urls.length; index = index &lt; 0 ? index + urls.length : index; if (options['tileType'] == 1) { return satUrls[index].replace('{x}', x).replace('{y}', y).replace('{z}', z); } else { return urls[index].replace('{x}', x).replace('{y}', y).replace('{z}', z); } }, crossOrigin: 'Anonymous' }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * * 获取离线百度地图 --有偏移 未完成 * @param {any} config * @memberof BaseLayers */ _getBaiDuLayer_offline(options) { // 自定义分辨率和瓦片坐标系 var resolutions = []; var maxZoom = 18; // 计算百度使用的分辨率 for (var i = 0; i &lt;= maxZoom; i++) { resolutions[i] = Math.pow(2, maxZoom - i); } var tilegrid = new ol.tilegrid.TileGrid({ origin: [0, 0], resolutions: resolutions // 设置分辨率 }); let _options = objectAssign({}, { source: new ol.source.TileImage({ projection: 'EPSG:3857', tileGrid: tilegrid, tileUrlFunction: function (tileCoord, pixelRatio, proj) { var z = tileCoord[0]; var x = tileCoord[1]; var y = tileCoord[2]; // 百度瓦片服务url将负数使用M前缀来标识 if (x &lt; 0) { x = -x; } if (y &lt; 0) { y = -y; } return &quot;&quot;+options['url']+&quot;/&quot; + z + &quot;/&quot; + x + &quot;/&quot; + y + &quot;.jpg&quot;; } }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * * 获取在线谷歌地图 * @param {any} options * @memberof BaseLayers */ _getGoogleLayer_online(options) { let url; switch (options['tileType']) { case 0: url = 'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i345013117!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0'; break; case 1: url = 'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmapSatellite!4e0!5m1!1e0'; break; case 2: url = 'http://mt1.google.cn/maps/vt?lyrs=s%40742&amp;hl=zh-Hans-CN&amp;gl=CN&amp;x={x}&amp;y={y}&amp;z={z}'; break; case 3: url = 'http://www.google.cn/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e4!2st!3i393!2m3!1e0!2sr!3i393087804!3m12!2szh-Hans-CN!3sCN!5e78!12m4!1e68!2m2!1sset!2sTerrain!12m3!1e37!2m1!1ssmartmaps!4e0!5m1!5f2'; break; case 4: url= 'http://mt1.google.cn/vt/lyrs=s@131,r@240000000&amp;hl=zh-CN&amp;gl=cn&amp;x={x}&amp;y={y}&amp;z={z}&amp;s=Gali'; break; } let _options = objectAssign({}, { source: new ol.source.XYZ({ //crossOrigin:'anonymous', crossOrigin:'*', url: url }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * * 获取离线谷歌地图 * @param {any} options * @memberof BaseLayers */ _getGoogleLayer_offline(options) { let _options = objectAssign({}, { source: new ol.source.XYZ({ url: options['url'] }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } /** * 获取arcgis切片 */ _getArcGisLayer_offline(options) { var _this = this; let _options = objectAssign({}, { source: new ol.source.XYZ({ tileUrlFunction: function(tileCoord){ var x = 'C' + _this.zeroPad(tileCoord[1], 8, 16); var y = 'R' + _this.zeroPad(-tileCoord[2] - 1, 8, 16); var z = 'L' + _this.zeroPad(tileCoord[0], 2, 10); var png = options['url'] + z + '/' + y + '/' + x + '.png'; // 'tilemap/bhxq/Layers/_alllayers/' return png; }, projection: 'EPSG:3857' }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } _getAArcGis_server(options){ let _options = objectAssign({}, { //extent:config.option.extent, source: new ol.source.TileArcGISRest({ url: options.url }) }, options); let baseLayer = new ol.layer.Tile(_options); return baseLayer; } zeroPad(num, len, radix){ var str = num.toString(radix || 10); while (str.length &lt; len){ str = &quot;0&quot; + str; } return str; } /** * * geojson * @param {any} options * @memberof BaseLayers */ _getGeoJson(options) { if (!options['url']) { throw new Error('geojson url 不能为空') } let vectorSource = new ol.source.Vector({ url: options['url'], format: new ol.format.GeoJSON() }); let _options = objectAssign({}, { source: vectorSource, crossOrigin: 'Anonymous', }, options); let vectorLayer = new ol.layer.Vector(_options); return vectorLayer; } /** * * kljson * @param {any} options * @memberof BaseLayers */ _getKlJson(options) { var _this = this; var klData = {}; if (typeof ($) == 'undefined') { throw new Error('依赖jquery,请引用jquery') } if (!options['url'] &amp;&amp; !options['isDynamic']) { throw new Error('kljson url 不能为空') } let styleFun = function (feature) { let prop = feature.getProperties(); let items = klData.items; let item = items[0]; let style = item.style; let field = klData.field; var b = klData.breaks; var type = klData.type; if (feature.get('_hidden')) return null; let polygonStyle = null; switch(type){ case 'break': //处理三角网格的kljson for(var i=0;i&lt;b.length;i++){ let item = items[i]; let style = item.style; if(prop[field]&lt;=b[i]){ polygonStyle=new ol.style.Style({ stroke: new ol.style.Stroke(style['stroke']), fill: new ol.style.Fill(style['fill']) }); break; } } if(prop[field]&gt;b[b.length-1/*i*/]){ let style = items[items.length-1].style; polygonStyle=new ol.style.Style({ stroke: new ol.style.Stroke(style['stroke']), fill: new ol.style.Fill(style['fill']) }); } break; case 'single': //只有单个样式 let image; if(style['image'] &amp;&amp; style['image'][&quot;xt&quot;]==&quot;circle&quot;){ image = new ol.style.Circle({ radius: (style[&quot;image&quot;]['radius']), fill: new ol.style.Fill(style[&quot;image&quot;]['fill']), // radius:4, // fill: null, stroke: new ol.style.Stroke({color: 'red', width: 1}) }); polygonStyle = new ol.style.Style({ image: image }) }else{ if(style['fill']){ polygonStyle=new ol.style.Style({ stroke: new ol.style.Stroke(style['stroke']), fill: new ol.style.Fill(style['fill']) }); }else{ polygonStyle=new ol.style.Style({ stroke: new ol.style.Stroke(style['stroke']) }); } } break; case 'icon': // if(items.length == 1){ // polygonStyle = new ol.style.Style({ // image: new ol.style.Icon({ // src: style.image.src // }) // }); // }else{ for(var i=0;i&lt;items.length;i++){ let item = items[i]; let style = item.style; let imageStyle = style.image; if(prop[&quot;type&quot;]==item[&quot;type&quot;]){ polygonStyle = new ol.style.Style({ image: new ol.style.Icon({ src: imageStyle.src, scale:imageStyle.scale // ,anchor : [imageStyle.anchor[0],imageStyle.anchor[1]] }) }); break; } } // } break; default: for (let i = 0; i &lt; items.length; i++) { let item = items[i]; if (item.value == prop[field]) { let style = item.style; // console.log(_this.json2obj(style,'style')) polygonStyle = new ol.style.Style({ stroke: new ol.style.Stroke(style['stroke']), fill: new ol.style.Fill(style['fill']) }) break; } } break; } return polygonStyle; } let _options = objectAssign({}, { // crossOrigin: 'Anonymous', crossOrigin:'*', style: styleFun }, options); let vectorLayer = new ol.layer.Vector(_options); $.ajaxSettings.async = false; //调用使用 // $.ajax({ // url: options['url'], // datatype: &quot;json&quot;, // type: 'get', // success: function (data) { // //成功后回调 // // alert(&quot;回调函数成功了&quot;); // var data = JSON.parse(data); // let vectorSource = new ol.source.Vector(); // let geo = data.geodata; // klData = data.style; // let type = data.type; // if(geo) { // if (geo.type == &quot;Topology&quot;) { // vectorSource.addFeatures((new ol.format.TopoJSON()).readFeatures(geo)); // } else if (geo.type) { // vectorSource.addFeatures((new ol.format.GeoJSON()).readFeatures(geo)); // } // } // vectorLayer.setSource(vectorSource); // }, // error: function(e){ // //失败后回调 // //alert(&quot;服务器请求失败&quot;); // }, // beforeSend: function(){ // //发送请求前调用，可以放一些&quot;正在加载&quot;之类额话 // //alert(&quot;正在加载&quot;); // }}) options['url'] &amp;&amp; $.getJSON(options['url'], function (data) { let vectorSource = new ol.source.Vector(); let geo = data.geodata; klData = data.style; let type = data.type; if(geo){ if (geo.type == &quot;Topology&quot;) { vectorSource.addFeatures((new ol.format.TopoJSON()).readFeatures(geo)); } else if (geo.type) { vectorSource.addFeatures((new ol.format.GeoJSON()).readFeatures(geo)); } } vectorLayer.setSource(vectorSource); }) return vectorLayer; } upfchar(xt){ return xt.substr(0,1).toUpperCase()+xt.substring(1); } json2obj (json, prop){ this.clzzMap = { 'fill':'ol.style.Fill', 'text':'ol.style.Text', 'circle':'ol.style.Circle', 'stroke':'ol.style.Stroke', 'icon':'ol.style.Icon' }; if(!json) return null; var obj=this.clone(json); var clzz=this.clzzMap[prop]; if(!clzz){ if(obj.xt){ clzz=this.clzzMap[obj.xt]; if(!clzz) clzz='ol.'+prop+'.'+this.upfchar(obj.xt); }else{ clzz='ol.'+prop+'.'+this.upfchar(prop); } } $.each(obj,function(value,key,self){ //console.log(arguments); if(typeof(value)=='object' &amp;&amp; !Array.isArray(value)){ self[key]=this.json2obj(value,key); } console.log(key); console.log(value); },this); console.log(clzz); console.log(obj); return objectAssign({},clzz,obj); } clone(obj) { var o; if (typeof obj == &quot;object&quot;) { if (obj === null) { o = null; } else { if (obj instanceof Array) { o = []; for (var i = 0, len = obj.length; i &lt; len; i++) { o.push(clone(obj[i])); } } else { o = {}; for (var j in obj) { o[j] = this.clone(obj[j]); } } } } else { o = obj; } return o; } /** * Images WMS 方式加载 * @param layerConfig * @private */ _getImageWMSLayer(layerConfig) { let layerName = layerConfig['layerName'] || '' layerConfig['addLayer'] = false layerConfig['create'] = true let layer = this.createImageWMSLayer(layerName, layerConfig) return layer } //与MapTool配合使用，可移植到其他页面，并作为临时图层 crtLayer(){ var sourceM = this._sourceM = new ol.source.Vector({ wrapX: false }); var layerM = this._layerM = new ol.layer.Vector({ id: 'measureLayer', source: sourceM, style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }) }); layerM.setZIndex(122); this.map.addLayer(layerM); var sourceMarker = this._sourceMa = new ol.source.Vector({ wrapX: false }); var layerMarker = this._layerMa = new ol.layer.Vector({ id: 'markLayer', source: sourceMarker, style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), // image: new ol.style.Icon({ // src: 'js/app/frmwk/gis/images/marker.png' // }) }) }); layerMarker.setZIndex(222); this.map.addLayer(layerMarker); } } export default BaseLayers × Search results Close "},"utils_CoordsTransform.js.html":{"id":"utils_CoordsTransform.js.html","title":"Source: utils/CoordsTransform.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: utils/CoordsTransform.js import { PI, x_PI, a, ee } from '../constants' class CoordsTransform { /** * 转换纬度 * @param lng * @param lat * @returns {number} */ transformlat(lng, lat) { let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; return ret } /** * 转换经度 * @param lng * @param lat * @returns {number} */ transformlng(lng, lat) { let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; return ret } /** * 判断坐标是否在国内（国外坐标不需转换） * @param lng * @param lat * @returns {boolean} */ outOfChina(lng, lat) { // 纬度3.86~53.55,经度73.66~135.05 return !(lng &gt; 73.66 &amp;&amp; lng &lt; 135.05 &amp;&amp; lat &gt; 3.86 &amp;&amp; lat &lt; 53.55); } /** * 国测局J02（火星坐标系 (GCJ-02)）坐标转WGS84 * @param lng * @param lat * @returns {[*,*]} */ gcj02towgs84(lng, lat) { if (this.outOfChina(lng, lat)) { return [lng, lat] } else { let dlat = this.transformlat(lng - 105.0, lat - 35.0); let dlng = this.transformlng(lng - 105.0, lat - 35.0); let radlat = lat / 180.0 * PI; let magic = Math.sin(radlat); magic = 1 - ee * magic * magic; let sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI); let mglat = lat + dlat; let mglng = lng + dlng; return [lng * 2 - mglng, lat * 2 - mglat] } } /** * WGS84转国测局J02（火星坐标系 (GCJ-02)） * @param lng * @param lat * @returns {[*,*]} */ wgs84togcj02(lng, lat) { if (this.outOfChina(lng, lat)) { return [lng, lat] } else { let dlat = this.transformlat(lng - 105.0, lat - 35.0); let dlng = this.transformlng(lng - 105.0, lat - 35.0); let radlat = lat / 180.0 * PI; let magic = Math.sin(radlat); magic = 1 - ee * magic * magic; let sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI); let mglat = lat + dlat; let mglng = lng + dlng; return [mglng, mglat] } } /** * 国测局J02（火星坐标系 (GCJ-02)）转百度坐标系 * @param lng * @param lat * @returns {[*,*]} */ gcj02tobd(lng, lat) { let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI); let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI); let bd_lng = z * Math.cos(theta) + 0.0065; let bd_lat = z * Math.sin(theta) + 0.006; return [bd_lng, bd_lat] } /** * 百度坐标系转国测局J02（火星坐标系 (GCJ-02)） * @param bd_lon * @param bd_lat * @returns {[*,*]} */ bdtogcj02(bd_lon, bd_lat) { let x = bd_lon - 0.0065; let y = bd_lat - 0.006; let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI); let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI); let gg_lng = z * Math.cos(theta); let gg_lat = z * Math.sin(theta); return [gg_lng, gg_lat] } } export default CoordsTransform × Search results Close "},"plugins_CustomCircle.js.html":{"id":"plugins_CustomCircle.js.html","title":"Source: plugins/CustomCircle.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: plugins/CustomCircle.js /** * 周边搜索 插件 */ import { ol } from '../constants' class CustomCircle { constructor(map, options) { this.map = map; //当前map对象 this.options = options; //当前传输参数 this.sphere = new ol.Sphere(6378137); this.center = options.center; this.projection = this.map.getView().getProjection(); this.minRadius = 500; //最小半径 this.maxRadius = 5000000; //最大半径 this.defaultSrc = &quot;../example/images/marker.png&quot;; //默认中心点src样式 this.centerPoint = this.addCenterPoint(options.centerPoint ? (options.centerPoint.src ? options.centerPoint.src : this.defaultSrc) : this.defaultSrc); //中心点 this.distance = options.distance ? this.transformRadius(this.center, options.distance) : this.transformRadius(this.center, this.minRadius); this.unit = options.distance ? options.distance : this.minRadius; this.mouseIng = false; //移动状态 false (未移动)true (移动中) this.defaultStyle = new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(71, 129, 217, 0.2)' }), stroke: new ol.style.Stroke({ color: 'rgba(71, 129, 217, 1)', width: 1 }), image: new ol.style.Circle({ radius: 5, fill: new ol.style.Fill({ color: 'rgba(71, 129, 217, 0.2)' }) }) }); //默认样式 this.style = options.style ? options.style : this.defaultStyle; //圆的样式 this.feature = this.addRangeCircle(); //圆的feature this.editor = this.addEditor(); //编辑器 overlay } addCustomCircle() { //创建周边搜索插件 // 创建一个临时图层 目前先写着 之后调用另一个里的 创建图层的方法 let layer = new ol.layer.Vector({ source: new ol.source.Vector(), layerName: &quot;CustomCircle&quot; }); // 在map里添加该图层 this.map.addLayer(layer); //添加范围圆 layer.getSource().addFeature(this.feature); this.map.addOverlay(this.centerPoint); //添加编辑器 this.map.addOverlay(this.editor); // 开启拖拽事件 this.dragEditor(); //默认设置地图范围 //this.setSuitableExtent(); } /** * 创建范围圆 */ addRangeCircle() { let feature = new ol.Feature({ geometry: new ol.geom.Circle(this.center, this.distance) }); feature.setStyle(this.style); return feature; } /** * 创建中心点 * @param src * @returns {ol.Overlay} */ addCenterPoint(src) { let element = document.createElement(&quot;img&quot;); element.src = src; let centerPoint = new ol.Overlay({ element: element }); centerPoint.setPosition(this.center); return centerPoint; } /** * 创建编辑器 * @returns {ol.Overlay} */ addEditor() { let src = &quot;http://webmap0.map.bdstatic.com/wolfman/static/common/images/nbsearch_366e590.png&quot;; let editor = document.createElement(&quot;div&quot;); editor.setAttribute(&quot;id&quot;, &quot;editor&quot;); editor.style.width = &quot;100px&quot;; editor.style.height = &quot;20px&quot;; editor.style.position = &quot;relative&quot;; editor.style.left = &quot;-18px&quot;; editor.style.top = &quot;-7px&quot;; editor.style.overflow = &quot;hidden&quot;; let icon = document.createElement(&quot;img&quot;); icon.setAttribute(&quot;id&quot;, &quot;icon&quot;); icon.src = src; editor.appendChild(icon); editor.appendChild(this.addText()); let overlay = new ol.Overlay({ element: editor }); overlay.setPosition(this.feature.getGeometry().getLastCoordinate()); return overlay; } /** * 创建text文本器 * @returns {Element} */ addText() { let text = document.createElement(&quot;div&quot;); text.setAttribute(&quot;id&quot;, &quot;range&quot;); text.innerHTML = this.unit + &quot;m&quot;; text.style.width = &quot;63px&quot;; text.style.height = &quot;18px&quot;; text.style.lineHeight = &quot;18px&quot;; text.style.border = &quot;1px solid black&quot;; text.style.color = &quot;black&quot;; text.style.background = &quot;white&quot;; text.style.float = &quot;left&quot;; text.style.marginLeft = &quot;5px&quot;; text.style.textAlign = &quot;center&quot;; text.style.position = &quot;relative&quot;; text.style.left = &quot;30px&quot;; text.style.top = &quot;-24px&quot;; text.style.fontSize = &quot;12px&quot;; return text; } /** * 求取半径值 * @param coordinate 当前移动到的位置的坐标 * @returns {number} 返回圆的半径 */ getRadius(coordinate) { let radius = null; switch (this.projection.getCode()) { case &quot;EPSG:4326&quot;: radius = this.sphere.haversineDistance(this.center, coordinate); break; case &quot;EPSG:3857&quot;: case &quot;EPSG:102100&quot;: //求平方根 radius = Math.sqrt(Math.pow(coordinate[0] - this.center[0], 2) + Math.pow(coordinate[1] - this.center[1], 2)); break; } let unit = radius; radius = this.transformRadius(this.center, radius); /* if (unit &gt; this.maxRadius) { radius = this.transformRadius(this.center, this.maxRadius); unit = this.maxRadius; } else if (unit &lt; this.minRadius) { radius = this.transformRadius(this.center, this.minRadius); unit = this.minRadius; }*/ return { unit: unit, radius: radius }; } /** * 拖拽编辑器 */ dragEditor() { var self = this; document.onmouseup = function(evt) { self.mouseIng = false; self.options.successCallback(self._getGeometry(), self._getCenter(), self._getRadius()) }; this.editor.getElement().onmousedown = function(evt) { self.mouseIng = true; }; this.map.on(&quot;pointermove&quot;, function(event) { if (self.mouseIng) { let radius = self.getRadius(event.coordinate); //重新设置圆的半径 self.feature.getGeometry().setRadius(radius[&quot;radius&quot;]); //重新设置 text值 let text = document.getElementById(&quot;range&quot;); text.innerHTML = parseInt(radius[&quot;unit&quot;]) + &quot;m&quot;; //重新设置overlay位置 self.editor.setPosition(self.feature.getGeometry().getLastCoordinate()); //给其适当范围 /*self.map.getLayers().forEach(function (layer) { layer.setExtent(self._getGeometry().getExtent()) })*/ //console.info() } }) } /** * 半径和坐标间的转换 * @param center * @param meterRadius * @returns {number} */ transformRadius(center, meterRadius) { let transformRadiu = 0; switch (this.projection.getCode()) { case 'EPSG:4326': let lastcoord = new ol.Sphere(6378137).offset(center, meterRadius, (270 / 360) * 2 * Math.PI); //计算偏移量 let dx = center[0] - lastcoord[0]; let dy = center[1] - lastcoord[1]; transformRadiu = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); break; case 'EPSG:3857': case 'EPSG:102100': transformRadiu = meterRadius; break; } return transformRadiu } /** * 将地图缩放到合适的范围 */ setSuitableExtent() { let extent = this._getGeometry().getExtent(); let center = ol.extent.getCenter(extent) var size = this.map.getSize(); this.map.getView().setCenter(center) this.map.getView().fit(extent, size) } /** * 获取圆的geometry * @private */ _getGeometry() { return this.feature.getGeometry() } /** * 获取圆的中心点 * @returns {ol.Coordinate|ol.Coordinate|undefined|*} * @private */ _getCenter() { return this._getGeometry().getCenter() } /** * 获取圆的半径 * @returns {number|*} * @private */ _getRadius() { return this._getGeometry().getRadius() } /** * 获取圆的线上的坐标 * @private */ _getCoordinates() { return this._getGeometry().getCoordinates() } /** * 获取圆的第一个坐标 * @returns {*} * @private */ _getFirstCoordinate() { return this._getCoordinates()[0] } /** * 获取圆的最后一个坐标 * @returns {*} * @private */ _getLastCoordinate() { return this._getCoordinates()[this._getCoordinates().length - 1] } /** * 设置圆的半径 * @param radius 半径长度 * @private */ _setRadius(radius) { this._getGeometry().setRadius(radius) } /** * 设置圆的圆心 * @param center 圆心坐标[x,y] * @private */ _setCenter(center) { this._getGeometry().setCenter(center) } /** * 设置中心点 样式 * @param src 图片的路径 * @private */ _setCenterPoint(src) { let element = this.centerPoint.getElement(); element.src = src; } } export default CustomCircle × Search results Close "},"event_Event.js.html":{"id":"event_Event.js.html","title":"Source: event/Event.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: event/Event.js /** * Created by FDD on 2017/8/8. */ class Event { constructor (type) { /** * @type {boolean} */ this.propagationStopped /** * The event type. * @type {string} * @api */ this.type = type /** * The event target. * @type {Object} * @api */ this.target = null } /** * Stop event propagation. * @function * @override * @api */ preventDefault () { this.propagationStopped = true } /** * Stop event propagation. * @function * @override * @api */ stopPropagation () { this.propagationStopped = true } /** * stopPropagation * @param evt */ static stopPropagation = (evt) =&gt; { evt.stopPropagation() } /** * preventDefault * @param evt */ static preventDefault = (evt) =&gt; { evt.preventDefault() } } export default Event × Search results Close "},"pointer_EventSource.js.html":{"id":"pointer_EventSource.js.html","title":"Source: pointer/EventSource.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/EventSource.js class EventSource { constructor (dispatcher, mapping) { /** * @type {PointerEventHandler} */ this.dispatcher = dispatcher /** * @private * @const * @type {!Object.&lt;string, function(Event)&gt;} */ this.mapping_ = mapping } /** * List of events supported by this source. * @returns {Array} */ getEvents () { return Object.keys(this.mapping_) } /** * Returns the handler that should handle a given event type. * @param eventType * @returns {function(Event)} */ getHandlerForEvent (eventType) { return this.mapping_[eventType] } } export default EventSource × Search results Close "},"event_EventTarget.js.html":{"id":"event_EventTarget.js.html","title":"Source: event/EventTarget.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: event/EventTarget.js /** * @classdesc * A simplified implementation of the W3C DOM Level 2 EventTarget interface. * @see {@link https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget} * * There are two important simplifications compared to the specification: * * 1. The handling of `useCapture` in `addEventListener` and * `removeEventListener`. There is no real capture model. * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`. * There is no event target hierarchy. When a listener calls * `stopPropagation` or `preventDefault` on an event object, it means that no * more listeners after this one will be called. Same as when the listener * returns false. */ import * as Events from './Events' import Event from './Event' class EventTarget { constructor () { /** * @private * @type {!Object.&lt;string, number&gt;} */ this.pendingRemovals_ = {} /** * @private * @type {!Object.&lt;string, number&gt;} */ this.dispatching_ = {} /** * @private * @type {!Object} */ this.listeners_ = {} } /** * addEventListener * @param type * @param listener */ addEventListener (type, listener) { let listeners = this.listeners_[type] if (!listeners) { listeners = this.listeners_[type] = [] } if (listeners.indexOf(listener) === -1) { listeners.push(listener) } } /** * dispatchEvent * @param event * @returns {*} */ dispatchEvent (event) { let evt = typeof event === 'string' ? new Event(event) : event let type = evt.type evt.target = this let listeners = this.listeners_[type] let propagate if (listeners) { if (!(type in this.dispatching_)) { this.dispatching_[type] = 0 this.pendingRemovals_[type] = 0 } ++this.dispatching_[type] for (var i = 0, ii = listeners.length; i &lt; ii; ++i) { if (listeners[i].call(this, evt) === false || evt.propagationStopped) { propagate = false break } } --this.dispatching_[type] if (this.dispatching_[type] === 0) { let pendingRemovals = this.pendingRemovals_[type] delete this.pendingRemovals_[type] while (pendingRemovals--) { this.removeEventListener(type, function () {}) } delete this.dispatching_[type] } return propagate } } /** * @inheritDoc */ disposeInternal () { Events.unlistenAll(this) } /** * getListeners * @param type * @returns {*} */ getListeners (type) { return this.listeners_[type] } /** * hasListener * @param optType * @returns {boolean} */ hasListener (optType) { return optType ? optType in this.listeners_ : Object.keys(this.listeners_).length &gt; 0 } /** * removeEventListener * @param type * @param listener */ removeEventListener (type, listener) { let listeners = this.listeners_[type] if (listeners) { let index = listeners.indexOf(listener) if (type in this.pendingRemovals_) { // make listener a no-op, and remove later in #dispatchEvent() listeners[index] = function () {} ++this.pendingRemovals_[type] } else { listeners.splice(index, 1) if (listeners.length === 0) { delete this.listeners_[type] } } } } } export default EventTarget × Search results Close "},"event_EventType.js.html":{"id":"event_EventType.js.html","title":"Source: event/EventType.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: event/EventType.js /** * Created by FDD on 2017/8/8. * @desc 事件类型 */ export const EventType = { CHANGE: 'change', CLICK: 'click', DBLCLICK: 'dblclick', DRAGENTER: 'dragenter', DRAGOVER: 'dragover', DROP: 'drop', ERROR: 'error', KEYDOWN: 'keydown', KEYPRESS: 'keypress', LOAD: 'load', MOUSEDOWN: 'mousedown', MOUSEMOVE: 'mousemove', MOUSEOUT: 'mouseout', MOUSEUP: 'mouseup', MOUSEWHEEL: 'mousewheel', MSPOINTERDOWN: 'MSPointerDown', RESIZE: 'resize', TOUCHSTART: 'touchstart', TOUCHMOVE: 'touchmove', TOUCHEND: 'touchend', WHEEL: 'wheel', POINTERMOVE: 'pointermove', POINTERDOWN: 'pointerdown', POINTERUP: 'pointerup', POINTEROVER: 'pointerover', POINTEROUT: 'pointerout', POINTERENTER: 'pointerenter', POINTERLEAVE: 'pointerleave', POINTERCANCEL: 'pointercancel' } × Search results Close "},"feature_Feature.js.html":{"id":"feature_Feature.js.html","title":"Source: feature/Feature.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: feature/Feature.js /* * @desc 要素相关处理 */ import { ol } from '../constants' import mix from '../utils/mixin' import Style from '../style/Style' import Layer from '../layer/Layer' class Feature extends mix(Style, Layer) { constructor(map) { super(); this.map = map; if (!this.map) { throw new Error('缺少地图对象！') } } /** * 通过id获取Feature * @param id * @returns {*} */ getFeatureById(id) { let layers = this.map.getLayers(), feature; layers.forEach(layer =&gt; { let source = layer.getSource(); if (source &amp;&amp; source.getFeatureById) { feature = source.getFeatureById(id); } }); return feature; } /** * 通过id和layerName获取Feature * （若在当前layerName查不到，则查询全部图层） * @param id * @param layerName * @returns {*} */ getFeatureById2LayerName(id, layerName) { let feature = null; if (!!layerName) { let layer = this.getLayerByName(layerName); if (layer &amp;&amp; layer instanceof ol.layer.Vector) { feature = layer.getSource().getFeatureById(id) } } if (!feature || !(feature instanceof ol.Feature)) { feature = this.getFeatureById(id); } return feature; } /** * 从属性信息中获取空间信息 * @param point * @returns {*} * @private */ _getGeometryFromPoint(point) { let geometry = null; if (point instanceof ol.geom.Geometry) { geometry = point; } else if (Array.isArray(point.geometry)) { geometry = new ol.geom.Point(point.geometry); } else { geometry = new ol.format.WKT().readGeometry(point.geometry); } return geometry; } /** * 获取当前范围 * @param multiFeatures * @private */ _getExtent(multiFeatures) { let extent = multiFeatures.getExtent(); let bExtent = true; for (let m = 0; m &lt; 4; m++) { if (extent[m] == Infinity || extent[m] == NaN) { bExtent = false; break; } } if (bExtent) { this.zoomToExtent(extent, true); } return extent; } /** * 调整当前要素范围 * @param extent * @returns {*} */ adjustExtent(extent) { if (this.map) { let width = ol.extent.getWidth(extent); let height = ol.extent.getHeight(extent); let adjust = 0.2; if (width &lt; 0.05) { let bleft = ol.extent.getBottomLeft(extent); //获取xmin,ymin let tright = ol.extent.getTopRight(extent); //获取xmax,ymax let xmin = bleft[0] - adjust; let ymin = bleft[1] - adjust; let xmax = tright[0] + adjust; let ymax = tright[1] + adjust; extent = ol.extent.buffer(extent, adjust); } return extent; } } /** * 缩放到当前范围 * @param extent * @param isanimation * @param duration */ zoomToExtent(extent, isanimation, duration) { if (this.map) { let view = this.map.getView(); let size = this.map.getSize(); /** * @type {ol.Coordinate} center The center of the view. */ let center = ol.extent.getCenter(extent); if (!isanimation) { view.fit(extent, size, { padding: [350, 200, 200, 350] }); view.setCenter(center); } else { if (!duration) { duration = 2000; view.animate({ center: center, duration: duration }); view.fit(extent, size); } } } }; /** * 判断点是否在视图内，如果不在地图将自动平移 */ movePointToView(coordinate) { if (this.map) { let extent = this.getMapCurrentExtent(); if (!(ol.extent.containsXY(extent, coordinate[0], coordinate[1]))) { this.map.getView().setCenter([coordinate[0], coordinate[1]]); } } } /** * 获取当前地图的范围 * @returns {ol.Extent} */ getMapCurrentExtent() { if (this.map) { return this.map.getView().calculateExtent(this.map.getSize()); } }; /** * 添加单点 * @param point * @param params * @returns {ol.Feature|ol.format.Feature|*|ol.render.Feature|Feature} */ addPoint(point, params) { let geometry = this._getGeometryFromPoint(point); let style = this.getStyleByPoint(point['attributes']); let feature = new ol.Feature({ geometry: geometry, params: params }); feature.setStyle(style); if (point['attributes'] &amp;&amp; (point['attributes']['id'] || point['attributes']['ID'])) { // let id = (point['attributes']['id'] ? point['attributes']['id'] : (point['attributes']['ID'] ? point['attributes']['ID'] : params['id'])); let id = (point.attributes['id'] || point.attributes['ID'] || params['id']); feature.setId(id); feature.setProperties(point['attributes']); } if (params['zoomToExtent']) { let coordinate = geometry.getCoordinates(); // extent = this.adjustExtent(extent); this.movePointToView(coordinate); } if (params['layerName']) { let layer = this.creatVectorLayer(params['layerName'], { create: true }); layer.getSource().addFeature(feature); } return feature; } /** * 添加多个点 * @param points * @param params */ addPoints(points, params) { if (points &amp;&amp; Array.isArray(points)) { let multiPoint = new ol.geom.MultiPoint([]), change = false; if (params['zoomToExtent']) { params['zoomToExtent'] = !params['zoomToExtent']; change = true; }; for (let i = 0; i &lt; points.length; i++) { let pointFeat = this.addPoint(points[i], params); multiPoint.appendPoint(pointFeat.getGeometry()); } if (change) { this._getExtent(multiPoint); } } } /** * 添加线要素 * @param line * @param params * @returns {*} */ addPolyline(line, params) { let linefeature = null; if (line.geometry.hasOwnProperty('paths')) { let feat = { 'type': 'Feature', 'geometry': { 'type': 'MultiLineString', 'coordinates': line.geometry.paths } }; linefeature = (new ol.format.GeoJSON()).readFeature(feat); } else { linefeature = new ol.Feature({ geometry: new ol.format.WKT().readGeometry(line.geometry) }); } let style = this.getStyleByLine(line['attributes']); let extent = linefeature.getGeometry().getExtent(); if (style &amp;&amp; linefeature) { linefeature.setStyle(style); } if (line['attributes'] &amp;&amp; (line.attributes['ID'] || line.attributes['id'])) { // let id = (line['attributes']['id'] ? line['attributes']['id'] : (line['attributes']['ID'] ? line['attributes']['ID'] : params['id'])); let id = (line.attributes['id'] || line.attributes['ID'] || params['id']); linefeature.setId(id); linefeature.setProperties(line.attributes); } if (params['zoomToExtent']) { this.zoomToExtent(extent, true); } if (params['layerName']) { let layer = this.creatVectorLayer(params['layerName'], { create: true }); layer.getSource().addFeature(linefeature); } return linefeature; } /** * 添加多条线要素 * @param lines * @param params */ addPolylines(lines, params) { if (lines &amp;&amp; Array.isArray(lines)) { let MultiLine = new ol.geom.MultiLineString([]), change = false; if (params['zoomToExtent']) { params['zoomToExtent'] = !params['zoomToExtent']; change = true; }; for (let i = 0; i &lt; lines.length; i++) { let polyLine = this.addPolyline(lines[i], params); MultiLine.appendLineString(polyLine.getGeometry()); } if (change) { this._getExtent(MultiLine); } } } /** * 添加面要素 * @param polygon * @param params * @returns {ol.render.Feature|ol.format.Feature|Feature|*|ol.Feature} */ addPolygon(polygon, params) { if (polygon &amp;&amp; polygon['geometry']) { let polygonFeature = new ol.Feature({ geometry: new ol.format.WKT().readGeometry(polygon.geometry) }); let style = this.getStyleByPolygon(polygon['attributes']); let extent = polygonFeature.getGeometry().getExtent(); if (style &amp;&amp; polygonFeature) { polygonFeature.setStyle(style); } if (polygon['attributes'] &amp;&amp; (polygon.attributes['ID'] || polygon.attributes['id'])) { let id = (polygon.attributes['id'] || polygon.attributes['ID'] || params['id']); polygonFeature.setId(id); polygonFeature.setProperties(polygon.attributes); } if (params['zoomToExtent']) { this.zoomToExtent(extent, true); } if (params['layerName']) { let layer = this.creatVectorLayer(params['layerName'], { create: true }); layer.getSource().addFeature(polygonFeature); } return polygonFeature; } else { console.info('传入的数据不标准！') } } /** * 添加多个面 * @param polygons * @param params */ addPolygons(polygons, params) { if (polygons &amp;&amp; Array.isArray(polygons)) { let MultiPolygon = new ol.geom.MultiPolygon([]), change = false; if (params['zoomToExtent']) { params['zoomToExtent'] = !params['zoomToExtent']; change = true; }; for (let i = 0; i &lt; polygons.length; i++) { let polygon = this.addPolyline(polygons[i], params); MultiPolygon.appendPolygon(polygon.getGeometry()); } if (change) { this._getExtent(MultiPolygon); } } } /** * 通过图层名移除要素 * @param layerName */ removeFeatureByLayerName(layerName) { try { let layer = this.getLayerByLayerName(layerName); if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource()) { layer.getSource().clear(); } } catch (e) { console.log(e) } } /** * 移除多个图层的要素 * @param layerNames &lt;Array&gt; */ removeFeatureByLayerNames(layerNames) { if (layerNames &amp;&amp; Array.isArray(layerNames) &amp;&amp; layerNames.length &gt; 0) { layerNames.forEach(item =&gt; { this.removeFeatureByLayerName(item); }) } else { console.info('id为空或者不是数组！') } } /** * 移除当前要素 * @param feature */ removeFeature(feature) { if (feature &amp;&amp; feature instanceof ol.Feature) { let tragetLayer = this.getLayerByFeatuer(feature); if (tragetLayer) { let source = tragetLayer.getSource(); if (source &amp;&amp; source.removeFeature) { source.removeFeature(feature); } } } else { throw new Error('传入的不是要素!') } } /** * 通过id移除要素 * @param id * @param layerName */ removeFeatureById(id, layerName) { if (this.map &amp;&amp; id) { if (layerName) { let layer = this.getLayerByLayerName(layerName); if (layer) { let feature = layer.getSource().getFeatureById(id); if (feature &amp;&amp; feature instanceof ol.Feature) { layer.getSource().removeFeature(feature); } } } else { let layers = this.map.getLayers().getArray(); layers.forEach(layer =&gt; { if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource()) { let feature = layer.getSource().getFeatureById(id); if (feature &amp;&amp; feature instanceof ol.Feature) { layer.getSource().removeFeature(feature); } } }); } } } /** * 移除多个要素 * @param ids * @param layerName */ removeFeatureByIds(ids, layerName) { if (ids &amp;&amp; Array.isArray(ids) &amp;&amp; ids.length &gt; 0) { ids.forEach(item =&gt; { this.removeFeatureById(item, layerName); }) } else { console.info('id为空或者不是数组！') } } } export {Feature} × Search results Close "},"map_Geolocation.js.html":{"id":"map_Geolocation.js.html","title":"Source: map/Geolocation.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/Geolocation.js import { ol } from '../constants' export class Geolocation { constructor (map, deviceid) { let previousM = 0; let deltaMean = 500; //地理位置变化采样周期（ms） let prePosition = null; let positions = null; let geolocation =null; let ekey = null; //绑定postcompose事件返回值 let timeoutid = null; //定时器编号 let ispause = false; //是否暂停的标志 let oddcoords = null; //暂停后剩下的轨迹点 let isnew = true; //是否新轨迹 this.previousM = 0; this.map = map; this._map = map; this.deviceid = '123'; this.crtInfoDiv(map); this.crtMarkerImage(map); this.init(this.deviceid); this.crtPathLayer(); } //创建用于显示定位点信息的div crtInfoDiv (map){ var info = document.createElement('div'); info.id = 'info_'+this.map.name; info.style.display = 'none'; info.style.cssText = 'float:right; position:absolute; width:200px; height:120px; top:110px; right:5px; background-color:#4c4e5a; z-index:2000; ' + 'border-width: 10px; border-radius: 10px; border-color: #000 #000 #000 #000; padding:10px; ' + 'font-size:14px; font-family:&quot;微软雅黑&quot;; color:#ffffff;'; var mdom = map.map.a; mdom.children[0].insertBefore(info, mdom.children[0].firstChild); //document.body.appendChild(info); } //创建Overlay容器 crtMarkerImage (map){ var img = document.createElement('img'); img.id = 'marker_'+this.map.name; img.src = './image/geolocation_marker.png'; //img.style.cssText = 'z-index:2001;'; var mdom = map.map.a; mdom.children[0].insertBefore(img, mdom.children[0].firstChild); //document.body.appendChild(img); } init (id){ // 创建导航定位标识的标注，添加到地图中 this.markerEl = document.getElementById('marker_'+this.map.name); this.marker = new ol.Overlay({ positioning: 'center-center', element: this.markerEl, stopEvent: false }); this._map.addOverlay(this.marker); // 定义用LineString存储轨迹点的地理位置信息（XYZM，Z维度用来存储角度/M则为时间维度） this.positions = new ol.geom.LineString([], /** @type {ol.geom.GeometryLayout} */ ('XYZM')); // 地理定位控件 this.geolocation = new ol.Geolocation(/** @type {olx.GeolocationOptions} */ ({ projection: this._map.getView().getProjection(), trackingOptions: { maximumAge: 10000, enableHighAccuracy: true, timeout: 600000 } })); //设置位置定位设备id this.geolocation.id = id; var _self=this; // 定位位置变化监听事件（添加定位点并更新轨迹面板信息） this.geolocation.on('change', function() { var position = _self.geolocation.getPosition(); var accuracy = _self.geolocation.getAccuracy(); var heading = _self.geolocation.getHeading() || 0; var speed = _self.geolocation.getSpeed() || 0; var m = Date.now(); _self.addPosition(position, heading, m, speed); //添加定位点 var coords = _self.positions.getCoordinates(); var len = coords.length; if (len &gt;= 2) { _self.deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1); } var html = [ 'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2), 'Accuracy: ' + accuracy, 'Heading: ' + Math.round(_self.radToDeg(heading)) + '&amp;deg;', 'Speed: ' + (speed * 3.6).toFixed(1) + ' km/h', 'Delta: ' + Math.round(_self.deltaMean) + 'ms' ].join('&lt;br /&gt;'); document.getElementById('info_'+_self.map.name).innerHTML = html; }); this.geolocation.on('error', function() { alert('geolocation error'); // FIXME we should remove the coordinates in positions }); /*this._map.beforeRender(function (map, frameState) { if (frameState !== null) { // 利用地理位置变化采样周期平稳变换过渡 var m = frameState.time - _self.deltaMean * 1.5; m = Math.max(m, _self.previousM); _self.previousM = m; // 沿模拟轨迹设置当前定位点的position var c = _self.positions.getCoordinateAtM(m, true); var view = frameState.viewState; if (c) { view.center = _self.getCenterWithHeading(c, -c[2], view.resolution);//设置地图中心点 view.rotation = -c[2];//设置地图旋转角度 _self.marker.setPosition(c);//设置导航定位点的标注位置 } } return true; // Force animation to continue });*/ } // 弧度转角度(°) radToDeg (rad) { return rad * 360 / (Math.PI * 2); } // 角度(°)转弧度 degToRad (deg) { return deg * Math.PI * 2 / 360; } // 负数求模 mod (n) { return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI); } addPosition (position, heading, m, speed) { var x = position[0]; var y = position[1]; var fCoords = this.positions.getCoordinates(); var previous = fCoords[fCoords.length - 1]; var prevHeading = previous &amp;&amp; previous[2]; if (prevHeading) { var headingDiff = heading - this.mod(prevHeading); // 强制变换角度（旋转角度变化不超过180度） if (Math.abs(headingDiff) &gt; Math.PI) { var sign = (headingDiff &gt;= 0) ? 1 : -1; headingDiff = -sign * (2 * Math.PI - Math.abs(headingDiff)); } heading = prevHeading + headingDiff; } this.positions.appendCoordinate([x, y, heading, m]); // 只保留20个最后的坐标 this.positions.setCoordinates(this.positions.getCoordinates().slice(-20)); // FIXME use speed instead if (heading &amp;&amp; speed) { //this.markerEl.src = 'js/app/frmwk/gis/images/geolocation_marker_heading.png'; this.markerEl.src = './image/geolocation_marker.png'; } else { this.markerEl.src = './image/geolocation_marker.png'; } } // 重新计算得到地图中心点（ by putting the given coordinates at 3/4 from the top or the screen） getCenterWithHeading (position, rotation, resolution) { var size = this._map.getSize(); var height = size[1]; return [ position[0] - Math.sin(rotation) * height * resolution * 1 / 4, position[1] + Math.cos(rotation) * height * resolution * 1 / 4 ]; } //var previousM = 0; updateView (me){ // 利用地理位置变化采样周期平稳变换过渡 var m = Date.now() - me.deltaMean * 1.5; m = Math.max(m, me.previousM); me.previousM = m; // 沿模拟轨迹设置当前定位点的position var c = me.positions.getCoordinateAtM(m, true); if (c) { var view = this._map.getView(); view.setCenter(_self.getCenterWithHeading(c, -c[2], view.getResolution())); view.setRotation(-c[2]); this.marker.setPosition(c); } } // 地图的postcompose 事件回调函数 render () { this.map.render();//渲染地图 } /** * 创建轨迹图层 */ crtPathLayer (){ this.trackSource = new ol.source.Vector(); var trackVector = new ol.layer.Vector({ source: this.trackSource, style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'red', lineDash: [1, 3, 5, 7], width: 2 }) }), // map: this._map }); this._map.addLayer(trackVector); } //两点连线 drawPath (first, second){ if(first != null){ var _first = [first[0], first[1]]/*[first.coords.longitude, first.coords.latitude]*/; //var projectedFirst = ol.proj.transform(_first, 'EPSG:4326', 'EPSG:3857'); var _second = [second[0], second[1]]/*[second.coords.longitude, second.coords.latitude]*/; //var projectedPosition = ol.proj.transform(_second, 'EPSG:4326', 'EPSG:3857'); //显示轨迹 var feature = new ol.Feature({ geometry: new ol.geom.LineString([_first, _second]) }); this.trackSource.addFeature(feature); this.trackSource.refresh(); } } soundMsg(){ //判断是否是ie var item = {}; if (!!window.ActiveXObject || &quot;ActiveXObject&quot; in window){ item = {html:'&lt;BGSOUND id=1 balance=0 src=&quot;resources/message.wav&quot; loop=&quot;1&quot;&gt;'}; }else{ item = {html:'&lt;audio id=1 balance=0 src=&quot;resources/message.wav&quot; autoplay=&quot;autoplay&quot;&gt;'}; } // var audio = Ext.widget({ // xtype:'container', floating: true,shadow:false,border:false,layout:'fit', // x:(-45),y:(-70),width:25,height:25,cls:'no-border', // items:[item] // }); // audio.show(); } /** * 预览轨迹 * 参数：points : 坐标串，格式[[x, y],... ] */ previewTrack (_pre){ var points = _pre.points,rep = _pre.rep,appmap = _APP.viewport.down('kmap[name=sy_map]'); this.trackSource.clear(); if(points.length &lt; 2) return; var first = points[0]; for(var i=1; i&lt;points.length; i++){ var second = points[i]; this.drawPath(first, second); first = second; } for(var j = 0; j &lt;rep.length; j++){ var point=[],div_infowin='div_page_map'+rep[j].event_code; point.push(rep[j].longitude); point.push(rep[j].latitude); point.div_infowin = div_infowin; appmap.showOverlay(point,200,250); // Ext.create('KPSFT.wsrc.controller.common.controller.ChartContainer',{ // width:200,height:250,floating:true,div_infowin:div_infowin,param:rep[j],name:rep[j].event_code, // clazz:'KPSFT.wsrc.controller.largeScreen.chart.EventInfo', // }); } this._map.getView().fit(this.trackSource.getExtent(), this._map.getSize()); document.getElementById('info_'+this.map.name).style.display=&quot;none&quot;; } /** * 播放历史轨迹 * 参数： {positions} json 字符串，结构如下： * [{ * &quot;coords&quot;: { * &quot;speed&quot;: 1.7330950498580933, * &quot;accuracy&quot;: 5, * &quot;altitudeAccuracy&quot;: 8, * &quot;altitude&quot;: 238, * &quot;longitude&quot;: 5.868668798362713, * &quot;heading&quot;: 67.5, * &quot;latitude&quot;: 45.64444874417562 * }, * &quot;timestamp&quot;: 1394788266115 * } * ... * ], * {isNew} boolean 是否新的轨迹 */ showTracking (_show, _new){ document.getElementById('info_'+this.map.name).style.display=&quot;none&quot;; var _self = this; if(!_show) return; var positions_ = _show.tra_data,rep = _show.rep, appmap = this.map;//appmap = _APP.viewport.down('kmap[name=sy_map]'); if(positions_.length == 0) return; _self.isnew = _new; //若为新的轨迹，将前次轨迹播放记录清除 if(_self.isnew){ _self.trackSource.clear(); } _self.prePosition = null; _self.positions = new ol.geom.LineString([], ('XYZM')); _self.clearTimeout(_self.timeoutid); //针对当前轨迹播放未完成，播放新轨迹的案例 _self.ispause = false; //每次播放前将暂停标识设置为false _self._map.getView().setZoom(17); _self.geolocation.setTracking(false); var coordinates = positions_; var first = coordinates.shift(); _self.tracking(first, false); //执行模拟位置变换功能 var old_po; for(var j = 0; j &lt;rep.length; j++){ if(rep[j].longitude == first.coords.longitude &amp;&amp; rep[j].latitude == first.coords.latitude ){ old_po=rep[j]; var point=[],div_infowin='div_page_map'+new Date().toLocaleString(); point.push(rep[j].longitude); point.push(rep[j].latitude); point.div_infowin = div_infowin; appmap.showOverlay(point,200,250); _self.soundMsg(); // Ext.create('KPSFT.wsrc.controller.common.controller.ChartContainer',{ // width:200,height:250,floating:true,div_infowin:div_infowin,param:rep[j], // clazz:'KPSFT.wsrc.controller.largeScreen.chart.EventInfo', // }); } } /***********************解决中断后再播放连续画轨迹的问题*****************/ var _first = [first.coords.longitude, first.coords.latitude]; _self.drawPath(_self.prePosition, _first); _self.prePosition = _first; /**************************************************************/ var prevDate = first.timestamp; var old_container; function geolocate() { _self.oddcoords = coordinates; // 将剩余的轨迹点保存 if (_self.ispause) { // 若启动暂停，则退出 _self.unEvent(_self.ekey); return; } var position = coordinates.shift(); if (!position) { return; } var newDate = position.timestamp; _self.tracking(position, false); // 执行模拟位置变换功能 // 创建定时器，每隔一定时间执行定位功能函数 _self.timeoutid = window.setTimeout(function() { for(var j = 0; j &lt;rep.length; j++){ if(rep[j].longitude == position.coords.longitude &amp;&amp; rep[j].latitude == position.coords.latitude &amp;&amp; (old_po?(old_po.longitude != rep[j].longitude &amp;&amp; old_po.latitude != rep[j].latitude &amp;&amp; old_po.event_code != rep[j].event_code):true)){ old_po=rep[j]; var point=[],div_infowin='div_page_map'+new Date().toLocaleString(); old_container=div_infowin; point.push(rep[j].longitude); point.push(rep[j].latitude); point.div_infowin = div_infowin; appmap.showOverlay(point,200,250); _self.soundMsg(); // Ext.create('KPSFT.wsrc.controller.common.controller.ChartContainer',{ // width:200,height:250,floating:true,div_infowin:div_infowin,param:rep[j], // clazz:'KPSFT.wsrc.controller.largeScreen.chart.EventInfo', // }); }else if(old_container &amp;&amp; (old_po.longitude!==position.coords.longitude || old_po.latitude!==position.coords.latitude) ){ var chartcontainer = document.getElementById(old_container) if(chartcontainer){ appmap.showOverlay(); old_container=undefined; var blingDiv = document.createElement('div'); $(blingDiv).data(&quot;eventData&quot;,old_po); $(blingDiv).data(&quot;position&quot;,[old_po.longitude,old_po.latitude]); blingDiv.id = 'blingbling'+old_po.event_code; blingDiv.className = 'blingbling'; blingDiv.innerHTML = '&lt;img class=&quot;imgidbling&quot; style=&quot;visibility:visible;z-index:99&quot; src=&quot;./image/guard.gif&quot; /&gt;'; var blingOverlay = new ol.Overlay({ id: 'blingbling'+old_po.event_code, element: blingDiv, position: [old_po.longitude,old_po.latitude], positioning: 'center-center', autoPan: true, autoPanAnimation: { duration: 250 //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度. 单位为毫秒（ms） } }); appmap.map.addOverlay(blingOverlay); blingDiv.onclick = function(e){ var detailWin=_APP.viewport.down('window[name=detailWin]'); if (detailWin) { detailWin.close(); } var type=''; if(old_po.event_status in [2,3,4]){ clazz='KPSFT.wsrc.controller.symap.floatWin.detailwin.chart.HSSJ'; }else if(old_po.event_status==5){ clazz='KPSFT.wsrc.controller.symap.floatWin.detailwin.chart.BJSJ'; } // detailWin=Ext.create('Ext.window.Window',{ // cls:'cls_hydrWin',bodyBorder : false,name:'detailWin',layout:'fit',constrain:true,closeAction: 'destroy', // width:1200,height:700, // items:[ // Ext.create(clazz,{ // param:{ // attributes: { // code:old_po.event_code, // event_idx:old_po.idx // } // } // }) // ] // }); // _APP.viewport.down('symap').down('container[name=sy_map]').add(detailWin); // detailWin.show(); } } } } prevDate = newDate; geolocate(); }, 2000 /*(newDate - prevDate) /0.5*/ ); // 播放结束取消地图一直居中 if (coordinates.length == 0 &amp;&amp; _self.ekey != null) { _self.unEvent(_self.ekey);//_self._map.unByKey(_self.ekey); } } geolocate(); _self.ekey = _self._map.on('postcompose',/*function () { _self._map.render();//渲染地图 }*/ function(){ var m = Date.now() - _self.deltaMean * 1.5; m = Math.max(m, _self.previousM); _self.previousM = m; // 沿着线坐标串插值 var c = _self.positions.getCoordinateAtM(m, true);// [x, y, z, m] if (c) { var view = _self._map.getView(); view.setCenter(_self.getCenterWithHeading(c, -c[2], view.getResolution())); // view.setRotation(-c[2]); _self.marker.setPosition(c); // 绘制轨迹(在此处绘制) _self.drawPath(_self.prePosition, c); _self.prePosition = c; } }); _self._map.render(); } /** * 实时定位 * 参数： {position} json 字符串，结构如下： * { * &quot;coords&quot;: { * &quot;speed&quot;: 1.7330950498580933, * &quot;accuracy&quot;: 5, * &quot;altitudeAccuracy&quot;: 8, * &quot;altitude&quot;: 238, * &quot;longitude&quot;: 5.868668798362713, * &quot;heading&quot;: 67.5, * &quot;latitude&quot;: 45.64444874417562 * }, * &quot;timestamp&quot;: 1394788266115 * } * {isDrawPath} 是否绘制轨迹标识 */ tracking (position, isDrawPath){ var _self = this; var coords = position.coords; _self.geolocation.set('accuracy', coords.accuracy); _self.geolocation.set('heading', this.degToRad(coords.heading)); var _position = [coords.longitude, coords.latitude]; /*var projectedPosition = ol.proj.transform(_position, 'EPSG:4326', 'EPSG:3857'); this.geolocation.set('position', projectedPosition);*/ _self.geolocation.set('position', _position); _self.geolocation.set('speed', coords.speed); _self.geolocation.changed(); if(isDrawPath){ /*if(!this.style){ this.style = new ol.style.Style({ stroke: new ol.style.Stroke({ color: style.color, lineDash: style.lineDash, width: style.width }) }); }*/ _self.drawPath(this.prePosition, position); _self.prePosition = position; //this.trackVector.setStyle(this.style); } } // 开启设备跟踪功能 setTracking (){ var _self = this; _self.geolocation.setTracking(true); // 开始位置跟踪 //this._map.on('postcompose', this.updateView(this)); _self._map.on('postcompose', function(){ var m = Date.now() - _self.deltaMean * 1.5; m = Math.max(m, _self.previousM); _self.previousM = m; // 沿着线坐标串插值 var c = _self.positions.getCoordinateAtM(m, true); if (c) { var view = _self._map.getView(); view.setCenter(_self.getCenterWithHeading(c, -c[2], view.getResolution())); view.setRotation(-c[2]); _self.marker.setPosition(c); } }); _self._map.render(); } /** * 设置轨迹播放暂停 */ setPause (){ var _self = this; _self.ispause = true; /*********解决中断后再播放轨迹不连续问题，待更好方法******/ var point = { &quot;coords&quot;: { &quot;speed&quot;: 0, &quot;accuracy&quot;:0, &quot;altitudeAccuracy&quot;:0, &quot;altitude&quot;: 0, &quot;longitude&quot;: _self.prePosition[0], &quot;heading&quot;: _self.prePosition[2], &quot;latitude&quot;: _self.prePosition[1] }, &quot;timestamp&quot;: _self.prePosition[3] }; _self.oddcoords.splice(0, 0,point); /*******************************************/ return _self.oddcoords; } /** * 继续播放暂停的轨迹 */ cancelPause (coords){ this.ispause = false; this.showTracking({tra_data:coords,rep:[]}, false); } /** * 清除轨迹,同时解除地图一直居中事件 */ clearPath (){ this.clearTimeout(this.timeoutid); this.trackSource.clear(); this.unEvent(this.ekey); document.getElementById('info_'+this.map.name).style.display=&quot;none&quot;; this._map.getView().setZoom(15); this._map.getView().setCenter([120.091, 30.635]); } /** * 根据key解除绑定事件 */ unEvent (ekey){ if(ekey != null){ ol.Observable.unByKey(ekey); } } /** * 清除定时程序 */ clearTimeout (id){ if(id != null){ window.clearTimeout(id); } } } export default Geolocation × Search results Close "},"main.js.html":{"id":"main.js.html","title":"Source: main.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: main.js /* *入口函数 * @Author: liuyang * @Date: 2017-09-17 11:01:58 * @Last Modified by: xuhongling * @Last Modified time: 2018-08-10 17:00:28 */ // message const version = require('../package.json').version const name = require('../package.json').name const author = require('../package.json').author // scss import './asset/scss/attribution.scss' import './asset/scss/index.scss' // ol.ext 内气泡样式 import './asset/scss/popupoverlay.scss' import './asset/scss/popupCustom.scss' import './asset/scss/gmaps-sidebar.scss' //阿里图表 import './asset/font-ali/iconfont.css' import './asset/font-ali/iconfont.eot' import './asset/font-ali/iconfont.svg' import './asset/font-ali/iconfont.ttf' import './asset/font-ali/iconfont.woff' import { ol } from './constants' import mixin from './utils/mixin' import Observable from './utils/observable-emit' // inter import * as _supported from './utils/supported' import { logo } from './asset/base64' import config from './config/config' import _Layer from './layer/Layer' import _Map from './map/Map' import _View from './map/View' import _BaseLayers from './map/BaseLayers' import _Controls from './map/Controls' import Geolocation from './map/Geolocation' import Tools from './map/Tools' import Sidebar from './map/Sidebar' // import ContextMenu from '../node_modules/ol-contextmenu' //用于webpack打包后无压缩版便于调试 import { isObject } from './utils/utils' import { EVENT_TYPE, INTERNAL_KEY } from './constants' window.ol = ol; // ol.ext 内气泡js require('./overlay/popupoverlay.js') // require('../node_modules/sidebar-v2/js/jquery-sidebar') require('./map/pulse') require('./plugins/resizeInit.js') var ContextMenu = require('./map/ContextMenu') //用于webpack打包后无压缩版便于调试 class GMap extends mixin( _Map, Observable, _View, _BaseLayers, _Controls, _Layer ) { constructor() { super() /** * 版权控件个数限制为1个 */ this.isHasAttribution = 0; /** * 当前版本 */ this.version_ = version this.Geolocation = Geolocation this.ContextMenu = ContextMenu this.Tools = Tools this.Sidebar = Sidebar /** * logo * @type {string} * @private */ this.logo_ = logo /** * 当前地图线要素 * @type {Array} */ this.currentMapLines = [] /** * 当前地图点要素 * @type {Array} */ this.currentMapPoints = [] /** * 当前地图面要素 * @type {Array} */ this.currentMapPolygon = [] /** * 当前地图线图层 * @type {Set} */ this.lineLayers = new Set() /** * 当前地图点图层 * @type {Set} */ this.pointLayers = new Set() /** * 当前地图面图层 * @type {Set} */ this.polygonLayers = new Set() /** * 选择交互 * @type {null} */ this.selectInteraction = null /** * 移动交互 * @type {null} */ this.moveInteraction = null /** * 当前选择要素 * @type {null} */ this.currentSelectFeature = null /** * 上一次选择要素 * @type {null} */ this.lastSelectFeature = null /** * 当前视图 * @type {null} */ this.view = null /** * 定时器 * @type {null} * @private */ this.timer_ = null /** * map * @type {null} */ this.map = null /** * 如果定义时给参数则直接初始化 */ let _arguments = Array.prototype.slice.call(arguments) if (_arguments.length === 1 &amp;&amp; isObject(_arguments[0])) { if (_arguments[0]['target']) { this.initMap(_arguments[0]['target'], _arguments[0]) } } else if (_arguments.length === 2 &amp;&amp; _arguments[0] &amp;&amp; isObject(_arguments[1])) { this.initMap(_arguments[0], _arguments[1]) } /** * 打印版本信息 */ this.showMassages_() Observable.call(this) } /** * 初始化当前地图 * @param mapDiv * @param params */ initMap(mapDiv, params = {}) { // try { /** * 地图的容器，元素本身或元素的id。如果在构建时未指定，则必须调用ol.Map＃setTarget才能呈现地图 */ this.target_ = mapDiv /** * 地图相关配置 * @type {{}} */ this.options_ = params /** * 当前视图 * @type ol.View */ this.view_ = this._addView(this.options_['view']) let logo = this._addCopyRight(this.options_['logo']) let layers = this.addBaseLayers(this.options_['baseLayers']) let controls = this._addControls(this.options_['controls']) /** * 当前地图对象 * @type {ol.Map} */ this.map = new ol.Map({ target: this.target_, loadTilesWhileAnimating: (typeof this.options_['loadTilesWhileAnimating'] === 'boolean' ? this.options_['loadTilesWhileAnimating'] : false), loadTilesWhileInteracting: (typeof this.options_['loadTilesWhileInteracting'] === 'boolean' ? this.options_['loadTilesWhileInteracting'] : false), logo: logo, layers: layers, view: this.view_, controls: controls, overlays:this.options_['overlays'] }) // 添加事件 this._addEvent() this._addMapInteraction() /** * 加载成功事件 */ this.dispatch(EVENT_TYPE.LOAD_MAP_SUCCESS, true) // } catch (error) { // this.dispatch(EVENT_TYPE.lo, error) // throw new Error(error) // } } /** * 添加事件 * @private */ _addEvent() { /** * 监听点击事件 */ // this.map.on(EVENT_TYPE.CLICK, e =&gt; { // this.dispatch(EVENT_TYPE.CLICK, e) // }) /** * 地图dom 改变大小时地图view刷新 */ $('#' +this.target_).bind('resize',{map:this.map},function(event) { event.data.map.updateSize(); }); /** * 监听点击事件 */ this.map.on(EVENT_TYPE.CLICK, e =&gt; { if (!this.map) return; let feature = null; let prop = null; if (e.originalEvent) { let pixel = this.map.getEventPixel(e.originalEvent); let flayer = this.map.forEachFeatureAtPixel(pixel, function (feature, layer) { if (layer) { let viewonly = layer.get('viewonly'); if (!viewonly) { return { feature: feature, layer: layer }; } } }); if (!flayer) { this.dispatch(EVENT_TYPE.CLICK, e) return } feature = flayer.feature; if (feature &amp;&amp; feature.getProperties) prop = feature.getProperties(); } this.dispatch(EVENT_TYPE.CLICK, prop, feature, this, e) }) /** * 监听双击事件 */ this.map.on(EVENT_TYPE.DBCLICK, event =&gt; { this.dispatch(EVENT_TYPE.DBCLICK, event) }) /** * 监听单击事件 */ this.map.on(EVENT_TYPE.SINGLECLICK, e =&gt; { if (!this.map) return; let feature = null; let prop = null; if (e.originalEvent) { let pixel = this.map.getEventPixel(e.originalEvent); let flayer = this.map.forEachFeatureAtPixel(pixel, function (feature, layer) { if (layer) { let viewonly = layer.get('viewonly'); if (!viewonly) { return { feature: feature, layer: layer }; } } }); if (!flayer) { this.dispatch(EVENT_TYPE.SINGLECLICK, e) return } feature = flayer.feature; if (feature &amp;&amp; feature.getProperties) prop = feature.getProperties(); } this.dispatch(EVENT_TYPE.SINGLECLICK, prop, feature, this, e) }) /** * 监听移动事件 */ this.map.on(EVENT_TYPE.POINTERMOVE, e =&gt; { if (!this.map) return; let feature = null; let prop = null; if (e.originalEvent) { let pixel = this.map.getEventPixel(e.originalEvent); let flayer = this.map.forEachFeatureAtPixel(pixel, function (feature, layer) { if (layer) { let viewonly = layer.get('viewonly'); if (!viewonly) { return { feature: feature, layer: layer }; } } }); if (!flayer) { this.dispatch(EVENT_TYPE.POINTERMOVE, e) return } feature = flayer.feature; if (feature &amp;&amp; feature.getProperties) prop = feature.getProperties(); } this.dispatch(EVENT_TYPE.POINTERMOVE, prop, feature, this, e) }) /** * 监听地图移动开始事件 */ this.map.on(EVENT_TYPE.MOVESTART, event =&gt; { this.dispatch(EVENT_TYPE.MOVESTART, event) }) /** * 监听地图移动结束事件 */ this.map.on(EVENT_TYPE.MOVEEND, event =&gt; { this.dispatch(EVENT_TYPE.MOVEEND, event) }) /** * 监听拖拽事件 */ this.map.on(EVENT_TYPE.POINTERDRAG, event =&gt; { this.dispatch(EVENT_TYPE.POINTERDRAG, event) }) /** * 监听移动事件 */ this.map.on(EVENT_TYPE.POINTERMOVE, event =&gt; { this.dispatch(EVENT_TYPE.POINTERMOVE, event) }) /** * 监听渲染完成事件 */ this.map.on(EVENT_TYPE.POSTCOMPOSE, event =&gt; { this.dispatch(EVENT_TYPE.POSTCOMPOSE, event) }) /** * 监听开始渲染事件 */ this.map.on(EVENT_TYPE.POSTRENDER, event =&gt; { this.dispatch(EVENT_TYPE.POSTRENDER, event) }) /** * 监听开始渲染之前 */ this.map.on(EVENT_TYPE.PRECOMPOSE, event =&gt; { this.dispatch(EVENT_TYPE.PRECOMPOSE, event) }) /** * 监听属性变化事件 */ this.map.on(EVENT_TYPE.PROPERTYCHANGE, event =&gt; { this.dispatch(EVENT_TYPE.PROPERTYCHANGE, event) }) /** * 监听change事件 */ this.map.on(EVENT_TYPE.CHANGE, event =&gt; { this.dispatch(EVENT_TYPE.CHANGE, event) }) /** * 监听图层组变化事件 */ this.map.on(EVENT_TYPE.CHANGELAYERGROUP, event =&gt; { this.dispatch(EVENT_TYPE.CHANGELAYERGROUP, event) }) /** * 监听大小变化事件 */ this.map.on(EVENT_TYPE.CHANGESIZE, event =&gt; { this.dispatch(EVENT_TYPE.CHANGESIZE, event) }) /** * 监听target变化事件 */ this.map.on(EVENT_TYPE.CHANGETARGET, event =&gt; { this.dispatch(EVENT_TYPE.CHANGETARGET, event) }) /** * 监听视图变化事件 */ this.map.on(EVENT_TYPE.CHANGEVIEW, event =&gt; { this.dispatch(EVENT_TYPE.CHANGEVIEW, event) }) } /** * 添加地图交互 * @private */ _addMapInteraction() { // 添加选中交互 this.selectInteraction = new ol.interaction.Select({ condition: ol.events.condition.click, style: function (feature, resolution) { return [ new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#D97363', width: 10 }) }) ] }, layers: function (layer) { return (layer.get(INTERNAL_KEY.SELECTABLE) === true) } }) // 添加鼠标移动交互 this.moveInteraction = new ol.interaction.Select({ condition: ol.events.condition.pointerMove, style: function (feature, resolution) { return [ new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#D97363', width: 10 }) }) ] }, layers: function (layer) { return (layer.get(INTERNAL_KEY.SELECTABLE) === true) }, filter: function (feat, layer) { if (feat.get('features')) { return feat.get('features').length &lt;= 1 } return true } }) this.moveInteraction.on('select', event =&gt; { let [selected, feature] = [event.selected, null] if (selected.length === 0) { let deselected = event.deselected if (deselected.length &gt; 0) { feature = deselected[0] this.unHighLightFeature('', feature, '') if (feature &amp;&amp; feature instanceof ol.Feature) { this.dispatch(EVENT_TYPE.FEATUREONMOUSEOUT, { type: EVENT_TYPE.FEATUREONMOUSEOUT, originEvent: event, value: feature }) } } } else { feature = selected[0] // 如果两个要素距离太近，会连续选中，而无法得到上一个选中的要素，所以在此保留起来 if (this.lastSelectFeature &amp;&amp; this.lastSelectFeature instanceof ol.Feature) { this.unHighLightFeature('', this.lastSelectFeature, '') this.lastSelectFeature = null } this.lastSelectFeature = feature this.highLightFeature('', feature, '') if (feature &amp;&amp; feature instanceof ol.Feature) { this.dispatch(EVENT_TYPE.FEATUREONMOUSEOVER, { type: EVENT_TYPE.FEATUREONMOUSEOVER, originEvent: event, value: feature }) } } }) this.selectInteraction.on('select', event =&gt; { let [selected, feature] = [event.selected, null] if (selected.length === 0) { let deselected = event.deselected if (deselected.length &gt; 0) { feature = deselected[0] this.unHighLightFeature('', feature, '') if (feature &amp;&amp; feature instanceof ol.Feature) { this.dispatch(EVENT_TYPE.FEATUREONDISSELECT, { type: EVENT_TYPE.FEATUREONDISSELECT, originEvent: event, value: feature }) } } } else { feature = selected[0] // 如果两个要素距离太近，会连续选中，而无法得到上一个选中的要素，所以在此保留起来 if (this.lastSelectFeature &amp;&amp; this.lastSelectFeature instanceof ol.Feature) { this.unHighLightFeature('', this.lastSelectFeature, '') this.lastSelectFeature = null } this.lastSelectFeature = feature this.highLightFeature('', feature, '') if (feature &amp;&amp; feature instanceof ol.Feature) { this.dispatch(EVENT_TYPE.FEATUREONSELECT, { type: EVENT_TYPE.FEATUREONSELECT, originEvent: event, value: feature }) } } }) this.map.addInteraction(this.moveInteraction) this.map.addInteraction(this.selectInteraction) } /** * 获取地图视图 * @public */ getView() { return this.map.getView() } /** * 添加要素选择事件 * @param event * @private */ _addFeatureSelectEvent(event) { let feature = this.map.forEachFeatureAtPixel(event.pixel, function (feature) { return feature }) if (feature &amp;&amp; feature instanceof ol.Feature) { this.dispatch(EVENT_TYPE.FEATUREONMOUSEOVER, { type: EVENT_TYPE.FEATUREONMOUSEOVER, originEvent: event, value: feature }) } } /** * 添加版权信息 * @returns {boolean} * @private */ _addCopyRight(params) { let logo = false if (params === true) { logo = { href: config.INDEX_URL, src: this.logo_ } } else if (isObject(params)) { logo = params } else { logo = false } return logo } /** * 显示相关信息 * @private */ showMassages_() { console.log(name, version, '©', author) } // static supported = _supported // static layer = _Layer // static get accessToken () { // return config.ACCESS_TOKEN // } // static set accessToken (token) { // config.ACCESS_TOKEN = token // } } export default GMap × Search results Close "},"layer_Layer.js.html":{"id":"layer_Layer.js.html","title":"Source: layer/Layer.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: layer/Layer.js import { ol } from '../constants' import mix from '../utils/mixin' import Style from '../style/Style' class Layer extends mix(Style) { constructor(map) { super(); this.map = map || null; if (!this.map) { throw new Error('缺少地图对象！') } } /** * 通过layerName获取图层 * @param layerName * @returns {*} */ getLayerByLayerName(layerName) { try { let targetLayer = null; if (this.map) { let layers = this.map.getLayers().getArray(); targetLayer = this.getLayerInternal(layers, 'layerName', layerName) } return targetLayer; } catch (e) { console.log(e); } } /** * 内部处理获取图层方法 * @param layers * @param key * @param value * @returns {*} */ getLayerInternal(layers, key, value) { let _target = null if (layers.length &gt; 0) { layers.every(layer =&gt; { if (layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() _target = this.getLayerInternal(layers, key, value) if (_target) { return false } else { return true } } else if (layer.get(key) === value) { _target = layer return false } else { return true } }) } return _target } /** * 通过键名键值获取图层集合（注意键名键值必须是set(key, value)） * @param key * @param value */ getLayersArrayByKeyValue(key, value) { try { let targetLayers = [] if (this.map) { let layers = this.map.getLayers().getArray() targetLayers = this.getLayersArrayInternal(layers, key, value) } return targetLayers } catch (e) { console.log(e) } } /** * 根据相关键值键名获取图层集合 * @param layers * @param key * @param value * @returns {Array} */ getLayersArrayInternal(layers, key, value) { let _target = [] if (layers.length &gt; 0) { layers.forEach(layer =&gt; { if (layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() let _layer = this.getLayersArrayInternal(layers, key, value) if (_layer) { _target = _target.concat(_layer) } } else if (layer.get(key) === value) { _target.push(layer) } }) } return _target } /** * 通过要素获取图层 * @param feature * @returns {*} */ getLayerByFeatuer(feature) { let tragetLayer = null if (this.map) { if (feature instanceof ol.Feature) { let layers = this.map.getLayers().getArray() layers.every(layer =&gt; { if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource) { let source = layer.getSource() if (source.getFeatures) { let features = source.getFeatures() features.every(feat =&gt; { if (feat === feature) { tragetLayer = layer return false } else { return true } }) } return false } else if (layer &amp;&amp; layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() layers.every(layer =&gt; { if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource) { let source = layer.getSource() if (source.getFeatures) { let features = source.getFeatures() features.every(feat =&gt; { if (feat === feature) { tragetLayer = layer return false } else { return true } }) } return true } else { return true; } }) } else { return true } }) } else { throw new Error('传入的不是要素!') } } return tragetLayer } /** * 创建临时图层 * @param layerName * @param params * @returns {*} */ creatVectorLayer(layerName, params) { try { if (this.map) { let vectorLayer = this.getLayerByLayerName(layerName); if (!(vectorLayer instanceof ol.layer.Vector)) { vectorLayer = null; } if (!vectorLayer) { if (params &amp;&amp; params.create) { vectorLayer = new ol.layer.Vector({ layerName: layerName, params: params, layerType: 'vector', source: new ol.source.Vector({ wrapX: false }), style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(67, 110, 238, 0.4)' }), stroke: new ol.style.Stroke({ color: '#4781d9', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }) }); } } if (this.map &amp;&amp; vectorLayer) { if (params &amp;&amp; params.hasOwnProperty('selectable')) { vectorLayer.set(&quot;selectable&quot;, params.selectable); } this.map.addLayer(vectorLayer); } return vectorLayer; } } catch (e) { console.log(e); } } /** * 创建专题图层 * @param layerName * @param params * @returns {*} */ creatTitleLayer(layerName, params) { let titleLayer = null; if (this.map) { let serviceUrl = params['serviceUrl']; if (!serviceUrl) return null; titleLayer = new ol.layer.Tile({ layerName: layerName, layerType: 'title', source: new ol.source.TileArcGISRest({ url: serviceUrl, params: params, wrapX: false }), wrapX: false }); this.map.addLayer(titleLayer) } return titleLayer; } /** * 创建ImageWMSLayer * @param layerName * @param params * @returns {string} */ createImageWMSLayer(layerName, params) { let layer = this.getLayerByLayerName(layerName) if (!(layer instanceof ol.layer.Image)) { layer = null } else if ((layer instanceof ol.layer.Image) &amp;&amp; !(params['addLayer'] === false)) { this.map.removeLayer(layer) layer = null } if (!layer &amp;&amp; params &amp;&amp; params['layerUrl'] &amp;&amp; params['create']) { layer = new ol.layer.Image({ layerName: layerName, visible: (params['isVisible'] === false) ? params['isVisible'] : true, opacity: (params['opacity'] &amp;&amp; (typeof params['opacity'] === 'number')) ? params['opacity'] : 1, source: new ol.source.ImageWMS({ url: params['layerUrl'], crossOrigin: (params['crossOrigin'] ? params['crossOrigin'] : undefined), params: { LAYERS: params['layers'], // require STYLES: params['style'] ? params['style'] : '', VERSION: params['version'] ? params['version'] : '1.3.0', WIDTH: params['width'] ? params['width'] : 256, HEIGHT: params['height'] ? params['height'] : 256, BBOX: params['bbox'], // require SRS: (params['srs'] ? params['srs'] : 'EPSG:3857'), CRS: (params['srs'] ? params['srs'] : 'EPSG:3857'), REQUEST: params['request'] ? params['request'] : 'GetMap', TRANSPARENT: true, TILED: (params['tiled'] === false) ? params['tiled'] : true, TILESORIGIN: (params['tiledsorrigin'] ? params['tiledsorrigin'] : undefined), SERVICE: 'WMS', FORMAT: (params['format'] ? params['format'] : 'image/png'), VIEWPARAMS: (params['viewparams'] ? params['viewparams'] : '') }, serverType: 'geoserver', wrapX: false }) }) } if (this.map &amp;&amp; layer &amp;&amp; !(params['addLayer'] === false)) { this.map.addLayer(layer) } return layer } /** * 移除图层 * @param layerName */ removeLayerByLayerName(layerName) { if (this.map) { let layer = this.getLayerByLayerName(layerName); if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource() &amp;&amp; layer.getSource().clear) { layer.getSource().clear(); } } } } export default Layer × Search results Close "},"constants.js.html":{"id":"constants.js.html","title":"Source: constants.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: constants.js /* * 静态常量 * @Author: liuyang * @Date: 2017-09-17 11:02:50 * @Last Modified by: liuyang * @Last Modified time: 2017-10-12 08:30:08 */ export const x_PI = 3.14159265358979324 * 3000.0 / 180.0; export const PI = 3.1415926535897932384626; // PI export const a = 6378245.0; // 北京54坐标系长半轴a=6378245m export const ee = 0.00669342162296594323; import _ol from '../node_modules/openlayers' import _projzh from '../node_modules/projzh' export const BASE_CLASS_NAME = { CLASS_HIDDEN: 'gmap-hidden', CLASS_SELECTABLE: 'gmap-selectable', CLASS_UNSELECTABLE: 'gmap-unselectable', CLASS_CONTROL: 'gmap-control' } export const ol = _ol; export const projzh = _projzh; /** * 图层默认配置项 */ export const layerConfigDefautls = { tileType: 0, isVisible: true, isDefault:true, layerName: '', crossOrigin: 'Anonymous', alias:'', attribution: { url: 'http://www.keepsoft.net/', title: '贵仁科技', messages: '版权所有' } }; export const EVENT_TYPE = { // 事件类型 LOAD_MAP_SUCCESS: 'loadMapSuccess', // 地图初始化成功事件 CLICK: 'click', // 点击事件 DBCLICK: 'dblclick', // 双击事件 SINGLECLICK: 'singleclick', // 单击事件 MOVESTART: 'movestart', // 地图开始移动事件 MOVEEND: 'moveend', // 地图结束移动事件 POINTERDRAG: 'pointerdrag', // 拖拽事件 POINTERMOVE: 'pointermove', // 移动事件 PRECOMPOSE: 'precompose', // 开始渲染之前 POSTRENDER: 'postrender', // 开始渲染 POSTCOMPOSE: 'postcompose', // 渲染完成 PROPERTYCHANGE: 'propertychange', // 属性变化 CHANGE: 'change', // change CHANGELAYERGROUP: 'change:layerGroup', // 图层组变化 CHANGESIZE: 'change:size', // 大小变化 CHANGETARGET: 'change:target', // target变化 CHANGEVIEW: 'change:view', // 视图变化 FEATUREONMOUSEOVER: 'feature:onmouseover', // 要素的鼠标移入事件 FEATUREONMOUSEOUT: 'feature:onmouseout', // 要素的鼠标移出事件 FEATUREONMOUSEDOWN: 'feature:onmousedown', // 要素鼠标按下 FEATUREONMOUSEUP: 'feature:onmouseup', // 要素鼠标抬起 FEATUREONMOVE: 'feature:onmove', // 要素移动 FEATUREONSELECT: 'feature:onselect', // 要素选中事件 FEATUREONDISSELECT: 'feature:ondisselect', // 要素取消选中事件 } export const INTERNAL_KEY = { // 自定义键值 SELECTABLE: 'selectable', // 要素是否可以被选择 MOVEABLE: 'moveable' // 要素是否可以被移动 } /** * ol 的常用style类型 */ export const OL_Style_Type={ 'fill':'ol.style.Fill', 'text':'ol.style.Text', 'circle':'ol.style.Circle', 'stroke':'ol.style.Stroke', 'icon':'ol.style.Icon' } × Search results Close "},"plugins_LayerSwitcher.js.html":{"id":"plugins_LayerSwitcher.js.html","title":"Source: plugins/LayerSwitcher.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: plugins/LayerSwitcher.js import { ol } from '../constants' class LayerSwitcher { constructor(map) { this.map = map || null; if (!this.map) { throw new Error('缺少地图对象！') } } /** * 获取当前底图（包含标注层） * @private */ _getBaseLayers() { if (this.map) { this.baseLayers = []; this.map.getLayers().getArray().forEach(layer =&gt; { if (layer &amp;&amp; layer instanceof ol.layer.Group &amp;&amp; layer.get('isBaseLayer')) { layer.getLayers().getArray().forEach(_layer =&gt; { if (_layer &amp;&amp; _layer instanceof ol.layer.Tile &amp;&amp; _layer.get('isBaseLayer')) { this.baseLayers.push(_layer); } }) } }) } } /** * 获取地图除标注层的layerNames * @returns {Array|*} */ getBaseLayerNames() { this._getBaseLayers(); this.baseLayerNames = []; if (this.baseLayers &amp;&amp; Array.isArray(this.baseLayers) &amp;&amp; this.baseLayers.length &gt; 0) { this.baseLayerNames = this.baseLayers.map(layer =&gt; { let layerName = ''; if (layer.get('layerNames') &amp;&amp; !layer.get('alias')) { layerName = layer.get('layerNames'); } return layerName }) } return this.baseLayerNames; } /** * 图层切换 * @param layerName */ switchLayer(layerName) { this._getBaseLayers(); this.baseLayers.forEach(layer =&gt; { if (layer.get('layerName') === layerName || layer.get('alias') === layerName) { layer.set('isDefault', true); layer.setVisible(true); } else { layer.set('isDefault', false); layer.setVisible(false); } }) } /** * 设置地图对象 * @param map * @returns {ol.Map} */ setMap(map) { if (map &amp;&amp; map instanceof ol.Map) { return this.map = map; } } /** * 获取地图对象 * @returns {*|null|ol.Map} */ getMap() { return this.map } } export default LayerSwitcher × Search results Close "},"asset_base64.js.html":{"id":"asset_base64.js.html","title":"Source: asset/base64.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: asset/base64.js /** * @desc 静态资源 */ /** * logo * @type {string} */ const logo = '' export { logo } × Search results Close "},"map_Map.js.html":{"id":"map_Map.js.html","title":"Source: map/Map.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/Map.js import { ol,layerConfigDefautls } from '../constants' const objectAssign = require('object-assign'); class Map { /** * 添加控件 * @param control */ addControl (control) { if (this.map &amp;&amp; control instanceof ol.control.Control) { this.map.addControl(control) } else { throw new Error('不存在地图或者传入控件对象有误！') } } /** * 添加交互 * @param interaction */ addInteraction (interaction) { if (this.map &amp;&amp; interaction instanceof ol.interaction.Interaction) { this.map.addInteraction(interaction) } else { throw new Error('不存在地图或者传入交互对象有误！') } } /** * 添加图层 * @param layer */ addLayer (layer) { let _this = this; if(Array.prototype.isPrototypeOf(layer)){ $.each(layer,function(i,e){ _this.map.addLayer(e) }) }else{ _this.map.addLayer(layer) } } /** *动态添加kljson */ addBaseLayer (config){ let options = objectAssign({}, layerConfigDefautls, config); let layer = this._getLayer(options); this.addLayer(layer); return layer; } /** * 通过json对象构造点要素 * @param jPoint 构造点要素的json对象，结构如下： * {coord: [lng, lat], * id: 'id', //要素id * style: {type: 'icon', //表示用图标渲染点要素 * src: 'fdata/image/XX.png', //图标来源 * rotation: 0.5, //旋转角度，单位：弧度 * offset: [10, 10], //相对点位的偏移量，单位：像素 * } | * { type: 'circle', //表示用圆渲染点要素 * radius: 7, //圆半径 * fcolor: 'red'|'rgba(r, g, b, a)', //填充颜色 * scolor: 'green'|'rgba(r, g, b, a)', //轮廓颜色 * width: 2, //轮廓宽度 * lineDash: [1, 3, 5, 7] //轮廓虚线样式 * } * } * @returns feature 点要素 */ addDynamicLayer (config,jPoint){ let options = objectAssign({}, layerConfigDefautls, config); let layer = this._getLayer(options); let psource = new ol.source.Vector(); if(Array.isArray(jPoint)){ var _this = this; $.each(jPoint,function(index, item){ var feature = _this.initPointFeature(item); psource.addFeature(feature); }); }else{ var feature = this.initPointFeature(jPoint); psource.addFeature(feature); } layer.setSource(psource); this.addLayer(layer); // this.map.getView().fit(psource.getExtent(), this.map.getSize()); } initPointFeature (jPoint){ var coord = jPoint.coord, style = jPoint.style; var feature = new ol.Feature({ geometry: new ol.geom.Point(coord), id: jPoint.id, type:jPoint.type }); feature.setStyle(this.crtStyle(style)); return feature; } /** * 根据json对象创建样式，结构如上函数所示 */ crtStyle (style){ var pstyle, type = style.type; if(type == 'icon'){ pstyle = new ol.style.Style({ image: new ol.style.Icon({ src: style.src, rotation: style.rotation, // offsetOrigin:'bottom-left', // offset: style.offset, size:style.size }) }); }else if(type == 'circle'){ pstyle = new ol.style.Style({ image: new ol.style.Circle({ fill: new ol.style.Fill({ color: style.fcolor }), radius: style.radius, stroke: new ol.style.Stroke({ color: style.scolor, width: style.width, lineDash: style.lineDash }) }) }); }else if(type == 'line'){ pstyle = new ol.style.Style({ stroke: new ol.style.Stroke({ color: style.color, width: style.width, lineDash: style.lineDash }) }) }else if(type == 'polygon'){ pstyle = new ol.style.Style({ stroke: new ol.style.Stroke({ color: style.scolor, width: style.width, lineDash: style.lineDash }), fill: new ol.style.Fill({ color: style.fcolor }) }) } return pstyle; } /** * 添加overlay * @param overlay */ addOverlay (overlay) { this.map.addOverlay(overlay) } /** * 增加修订计数器并调用change事件 */ changed () { this.map.changed() } /** * 触发事件 * @param event * @returns {boolean|undefined} */ dispatchEvent (event) { return this.map.dispatchEvent(event) } /** * 查找像素位置最近的要素 * @param pixel * @param callback * @param options * @returns {T|undefined} */ forEachFeatureAtPixel (pixel, callback, options) { return this.map.forEachFeatureAtPixel(pixel, callback, options) } /** * 查找像素位置的图层 * @param pixel * @param callback * @param optThis * @param optLayerFilter * @param optThis2 * @returns {T|undefined} */ forEachLayerAtPixel (pixel, callback, optThis, optLayerFilter, optThis2) { return this.map.forEachLayerAtPixel(pixel, callback, optThis, optLayerFilter, optThis2) } /** * 获取set的属性值 * @param key */ get (key) { return this.map.get(key) } /** * 获取使用的控件 * @returns {ol.Collection.&lt;ol.control.Control&gt;} */ getControls () { return this.map.getControls() } /** * 获取开启的所有交互 * @returns {ol.Collection.&lt;ol.interaction.Interaction&gt;} */ getInteractions () { return this.map.getInteractions() } /** * 获取像素位置对应的坐标 * @param pixel * @returns {ol.Coordinate} */ getCoordinateFromPixel (pixel) { return this.map.getCoordinateFromPixel(pixel) } /** * 获取坐标对应的像素 * @param coordinate * @returns {ol.Pixel} */ getPixelFromCoordinate (coordinate) { return this.map.getPixelFromCoordinate(coordinate) } /** * 返回事件触发位置的坐标 * @param event * @returns {ol.Coordinate} */ getEventCoordinate (event) { return this.map.getEventCoordinate(event) } /** * 返回事件触发位置的像素 * @param event * @returns {ol.Pixel} */ getEventPixel (event) { return this.map.getEventPixel(event) } /** * 获取像素位置的所有要素 * @param pixel * @param options * @returns {Array.&lt;ol.Feature|ol.render.Feature&gt;} */ getFeaturesAtPixel (pixel, options) { return this.map.getFeaturesAtPixel(pixel, options) } /** * 获取图层组 * @returns {ol.layer.Group} */ getLayerGroup () { return this.map.getLayerGroup() } /** * 获取地图上所有图层 * @returns {!ol.Collection.&lt;ol.layer.Base&gt;} */ getLayers () { return this.map.getLayers() } /** * 根据id获取Overlay * @param id * @returns {ol.Overlay} */ getOverlayById (id) { return this.map.getOverlayById(id) } /** * 获取地图上所有的overlay * @returns {ol.Collection.&lt;ol.Overlay&gt;} */ getOverlays () { return this.map.getOverlays() } /** * 获取属性 * @returns {Object.&lt;string, *&gt;} */ getProperties () { return this.map.getProperties() } /** * 获取修订计数器 * @returns {number} */ getRevision () { return this.map.getRevision() } /** * 获取地图尺寸 * @returns {ol.Size|undefined} */ getSize () { return this.map.getSize() } /** * 获取初始化地图的要素对象 * @returns {Element|string|undefined} */ getTarget () { return this.map.getTarget() } /** * 获取目标对象 * @returns {Element} */ getTargetElement () { return this.map.getTargetElement() } /** * 获取对象属性名称列表。 * @returns {Array.&lt;string&gt;} */ getKeys () { return this.map.getKeys() } /** * 获取视图对象 * @returns {ol.View} */ getView () { return this.map.getView() } /** * 获取用作地图视口的元素 * @returns {Element} */ getViewport () { return this.map.getViewport() } /** * 所在像素是否有要素 * @param pixel * @param options * @returns {boolean} */ hasFeatureAtPixel (pixel, options) { return this.map.hasFeatureAtPixel(pixel, options) } /** * 移除控件 * @param control * @returns {ol.control.Control|undefined} */ removeControl (control) { return this.map.removeControl(control) } /** * 移除交互 * @param interaction * @returns {ol.interaction.Interaction|undefined} */ removeInteraction (interaction) { return this.map.removeInteraction(interaction) } /** * 手动调用渲染器 */ render () { this.map.render() } /** * 以同步方式请求（立即渲染） * @param key * @param value * @param silent */ renderSync (key, value, silent) { this.map.renderSync(key, value, silent) } /** * 设置图层组 * @param layerGroup */ setLayerGroup (layerGroup) { this.map.setLayerGroup(layerGroup) } /** * 设置属性值 * @param values * @param silent &lt;更新而不触发事件&gt; */ setProperties (values, silent) { this.map.setProperties(values, silent) } /** * 设置地图大小 * @param size */ setSize (size) { this.map.setSize(size) } /** * 设置地图所在目标元素 * @param target */ setTarget (target) { this.map.setTarget(target) } /** * 获取当前地图 * @returns {ol.Map|*} */ getMap () { return this.map } /** * 设置地图实例 * @param map */ setMap (map) { if (map &amp;&amp; map instanceof ol.Map) { this.map = map } } /** * 重新设置视图 * @param view */ setView (view) { if (this.map &amp;&amp; view instanceof ol.View) { this.map.setView(view) } else { throw new Error('不存在地图或者传入视图对象有误！') } } /** * 取消属性 * @param key * @param silent */ unset (key, silent) { this.map.unset(key, silent) } /** * 更新地图大小 * @returns {ol.Map|*|null|_openlayers2.Map.default} */ updateSize () { if (this.map) { this.map.updateSize() return this.map } else { throw new Error('未实例化地图对象！') } } /** * 根据id 获取feature * @param {*} lyrName * @param {*} fid * @param {*} field */ getFeature(lyrName,fid,field){ var lyr=this.getLayerByLayerName(lyrName); var feature=null; var features = lyr.getSource().getFeatures(); for(var i=0; i&lt;features.length;i++){ if(features[i].getProperties()[field||'ID']==fid){ feature=features[i]; break; } } return feature; } /** * 居中定位不放大 * @param {*} lyrName * @param {*} fid * @param {*} field 与kljson对应的字段 */ focusAtFeatureNoZoom (lyrName,fid,field){ var feature= this.getFeature(lyrName,fid,field); this.zoomAtFeature(feature); return feature; } /** * 居中定位放大 * @param {*} lyrName * @param {*} fid * @param {*} field 与kljson对应的字段 */ focusAtFeature(lyrName,fid,field){ var fea = this.getFeature(lyrName,fid,field); var l = this.setMapLevel(fea); this.map.getView().setZoom(l); this.zoomAtFeature(fea); return fea; } /** * 根据fea设置显示层级 * @param {*} fea */ setMapLevel(fea){ var extent=fea.getGeometry().getExtent(); var xx=extent[2]-extent[0]; var yy=extent[3]-extent[1]; if(xx&gt;=yy){ xx=xx; }else{ xx=yy; } var level=13; if(0&lt;xx &amp;&amp; xx&lt;=100){ level=17; } if(xx&gt;100 &amp;&amp;xx&lt;=500){ level=16; } if(xx&gt;500 &amp;&amp;xx&lt;=1000){ level=15; } if(xx&gt;1000 ){ level=14; } return level; } /** * [添加脉冲效果] * @param {[Array]} coordinate [xy坐标] */ addPulse (coordinate) { if(!(this.map.pluses instanceof Array ))this.map.pluses=[]; this.map.pluses.push(coordinate); this.addPluseArr(); } addPluseArr(){ var _this = this; // map.pulse方法是扩充的，需要修改 $.each(this.map.pluses,function(index,e){ _this.map.pulse(true, e, { amplitude: 0.5, duration: 400, style: new ol.style.Style({ image: new ol.style.Circle({ radius: 15, points: 4, stroke: new ol.style.Stroke({ color: &quot;red&quot;, width: 2 }) }) }), easing: ol.easing.inAndOut } ); _this.map.pulse(false, e, { amplitude: 0.5, duration: 400, style: new ol.style.Style({ image: new ol.style.Circle({ radius: 15, points: 4, stroke: new ol.style.Stroke({ color: &quot;red&quot;, width: 2 }) }) }), easing: ol.easing.inAndOut } ) }) } /** * [取消脉冲效果] */ stopPulse(point) { var pluses = this.map.pluses; if(pluses.length == 0 || !arguments[0]||pluses.length == 1){ this.map.stopPulse(); } else { this.removeObjWithArr(pluses,point); this.addPluseArr(); } } /** * 取消脉冲 */ stopPulse (point){ if(point){ this.map.stopPulse(point); }else{ this.map.stopPulse(this.map.pluses); this.map.pluses = []; } } removeObjWithArr (_arr, _obj) { var length = _arr.length; for(var i = 0; i &lt; length; i++) { if(_arr[i][0] == _obj[0] &amp;&amp; _arr[i][1] == _obj[1]) { if(i == 0) { _arr.shift(); //删除并返回数组的第一个元素 return; } else if(i == length-1) { _arr.pop(); //删除并返回数组的最后一个元素 return; } else { _arr.splice(i,1); //删除下标为i的元素 return; } } } } /** * 导出地图成图片 */ exportMap(){ var obj = this; var today = new Date(); var date = '' + today.getFullYear() + this.getTwoLen((today.getMonth()+1)) + this.getTwoLen(today.getDate()) + this.getTwoLen(today.getHours()) + this.getTwoLen(today.getMinutes()) + this.getTwoLen(today.getSeconds()); this.map.once('postcompose', function(event) { var canvas = event.context.canvas; if (navigator.msSaveBlob) { navigator.msSaveBlob(canvas.msToBlob(), 'map'+ date +'.png'); } else { canvas.toBlob(function(blob) { saveAs(blob, 'map'+ date +'.png'); }); } }); this.map.renderSync(); } getTwoLen(num){ return num.toString().length==1?('0'+num):num; } /** * 修改图层 */ modifyMap(){ this.select = new ol.interaction.Select({ style:new ol.style.Style({ stroke: new ol.style.Stroke({ color: [0, 153, 255, 1], width: 5 }) }), wrapX: false }); this.map.addInteraction(this.select); this.modify = new ol.interaction.Modify({ features: this.select.getFeatures() }); this.map.addInteraction(this.modify); this.modify.on('modifyend',function(e){ var features = e.features.getArray(); targetFeature = features[0]; var wktInfo = new ol.format.WKT().writeFeature(targetFeature); console.log(wktInfo); }) } /** * 根据位置来显示自定义样式的气泡 * @param {*} position * @param {*} w * @param {*} h */ showOverlay (position, w,h){ var div_infowin = position &amp;&amp;position.div_infowin?position.div_infowin:&quot;div_infowin&quot;; if(!position) this.overlay.hide(); else{ var width=(w)?w:470; var height=(h)?h:320; var html='&lt;div id=&quot;'+div_infowin+'&quot; style=&quot;width:'+width+'px;height:'+height+'px;&quot;&gt;&lt;/div&gt;'; // var popup = new ol.Overlay({ // element: document.getElementById('popup') // }); this.overlay = new ol.Overlay.Popup ({ popupClass: &quot;default opacity8&quot;, closeBox: false, onclose: function(){ console.log(&quot;You close the box&quot;); }, positioning: 'auto', autoPan: false, autoPanAnimation: { duration: 250 } }); // popup.setPosition(position); this.map.addOverlay(this.overlay); this.overlay.show(position,html); } } /* 停止多选*/ resetDragBox(){ if(this._select){ this._select.getFeatures().clear(); this.map.removeInteraction(this._select); } if(this._dragBox) this.map.removeInteraction(this._dragBox); } startDragBox(lyrid,fn){ this._selectLayer=this.getLayerByLayerName(lyrid); this.resetDragBox(); this._select = new ol.interaction.Select(); this.map.addInteraction(this._select); this._dragBox = new ol.interaction.DragBox({ condition: ol.events.condition.noModifierKeys }); this.map.addInteraction(this._dragBox); this._dragBox.on('boxstart',this._dragBoxStart,this); this._dragBox.on('boxend',function(){ console.log(this); var extent = this._dragBox.getGeometry().getExtent(); var selectedFeatures = this._select.getFeatures(); var properties=[]; this._selectLayer.getSource().forEachFeatureIntersectingExtent(extent, function(feature) { if(feature.getProperties) properties.push(feature.getProperties()); selectedFeatures.push(feature); }); let r = { properties,extent,selectedFeatures} fn(r); },this); } _dragBoxStart(){ if(this._select){ this._select.getFeatures().clear(); } } /** * 开启绘制路线功能 * isCloseRoadDraw 是否封路（首尾有封路图标）和每个点都有图片区分 * roadCloseDraw 1 * mapid */ openLineString (isCloseRoadDraw,mapid){ var source = new ol.source.Vector(); var endPoint=[]; var arrow = '../assets/images/redCircle.png'; var lineWidth = 2; if(isCloseRoadDraw == 1){ //是否封路绘制 arrow ='../assets/images/roadClosed.png'; lineWidth= 12; } var styleFunction = function(feature) { var geometry = feature.getGeometry(); var imageStyle = new ol.style.Icon({ crossOrigin: '*', src: arrow, anchor: [0.75, 0.5], rotateWithView: true }); var firstPointStyle = new ol.style.Style({ stroke: new ol.style.Stroke({ lineDash:[1,2,3,4,5,6], color: '#f41800', width: lineWidth }), }); if(isCloseRoadDraw == 1){ firstPointStyle = new ol.style.Style({ //绘制成路段后路段的样式 stroke: new ol.style.Stroke({ color: &quot;#000000&quot;, width: 12, lineDash:[1, 20, 4, 5] }), }); } var styles = [firstPointStyle]; // linestring geometry.forEachSegment(function(start, end) { if(isCloseRoadDraw == 1){// 只会给最后点添加样式 if(styles.length == 1){ styles.push(new ol.style.Style({ geometry: new ol.geom.Point(start), image:imageStyle })); } }else{ styles.push(new ol.style.Style({ geometry: new ol.geom.Point(end), image:imageStyle })); styles.push(new ol.style.Style({ geometry: new ol.geom.Point(start), image:imageStyle })); } endPoint = end; }); if(isCloseRoadDraw == 1){ //道路封路首尾带图标的控制（针对内涝调度绘制） styles.push(new ol.style.Style({ geometry: new ol.geom.Point(endPoint), image:imageStyle })); } return styles; }; var vector = new ol.layer.Vector({ source: source, style: styleFunction, }); //线段文字标注 var style = new ol.style.Style({ text: new ol.style.Text({ font: 'bold 15px &quot;Open Sans&quot;, &quot;Arial Unicode MS&quot;, &quot;sans-serif&quot;', placement: 'line', fill: new ol.style.Fill({ color: 'white' }) }) }); var textPre = &quot;&quot;; var textVector = new ol.layer.Vector({ source:source, style: function(feature) { style.getText().setText(textPre); return style; }}); if(isCloseRoadDraw != 1){ //绘制后形成的路段带灰色的背景图层 var styleFunction2 = function(feature) { var geometry = feature.getGeometry(); var styles = [ // linestring new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#b0b4b7', width: 13 }) }) ]; return styles; }; var vector2 = new ol.layer.Vector({ source: source, style: styleFunction2 }); this.addLayer(vector2); } this.addLayer(vector); this.addLayer(textVector); var styleCloseRoadDraw = {} if(isCloseRoadDraw == 1){ //是否封路绘制-勾画线段样式 styleCloseRoadDraw = new ol.style.Style({ stroke: new ol.style.Stroke({ color: &quot;#000000&quot;, width: 12, lineDash:[1, 10, 4, 5] }), image:new ol.style.Icon({ crossOrigin: '*', src: arrow, anchor: [0.75, 0.5], rotateWithView: true }) }) }else{ styleCloseRoadDraw = new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'red', width: 5 }) }) } var draw = new ol.interaction.Draw({ source: source, type: 'LineString', style:styleCloseRoadDraw }); this.map.draw = draw; this.map.sourceByDraw = source; this.map.addInteraction(draw); var listener; //XXX:不需要监听此方法 draw.on('drawstart', function(evt) { }, this); draw.on('drawend', function(h) { var pointArray = h.target.a; this.showPopupOverlay(pointArray[pointArray.length-1],'','popup-black-drawclose',true,true,'ol-popup-black-drawclose',h.feature,mapid); ol.Observable.unByKey(listener); if(!this.map.pointArrays||this.map.pointArrays.length==0){ this.map.pointArrays = []; } this.map.pointArrays.push(pointArray); }, this); } /* * position 传入overlay的坐标信息 * contentdata 传入popup框中的内容 * id 传入overlay的id * triangle_ornot 是否要弹出框的小三角 * closer_ornot 是否要弹出框的关闭 * classStyle 从默认样式中选择 ['ol-popup-black',,'ol-popup-grey',,'ol-popup-white'] * mapid 地图dom id */ showPopupOverlay (position, contentdata, id, triangle_ornot, closer_ornot, classStyle,feature,mapid) { var container = document.createElement('div'); //创建poup框方法2 container.id = 'popup'; container.className = classStyle; var content = document.createElement('div'); content.id = 'popup-content'; content.className = classStyle+'-content'; $(&quot;#&quot; + mapid)[0].appendChild(container); container.appendChild(content); var overlay = new ol.Overlay(/** @type {olx.OverlayOptions} */ ({ id: id, element: container, autoPan: true, autoPanAnimation: { duration: 250 //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度. 单位为毫秒（ms） } })); if(triangle_ornot){ var conret = document.createElement('div'); conret.id = 'popup-triangle'; conret.className = classStyle+'-triangle'; container.appendChild(conret); } if(closer_ornot){ var closer = document.createElement('div'); closer.id = 'popup-closer'; closer.className = classStyle+'-closer'; container.appendChild(closer); if(feature){ var curDrawfeature = feature; var map = this.map; } closer.onclick = function() { overlay.setPosition(undefined); closer.blur(); curDrawfeature &amp;&amp; map.sourceByDraw.removeFeature(curDrawfeature); return false; }; } content.innerHTML = contentdata; overlay.setPosition(position); this.map.addOverlay(overlay); } /** * 开启地图右键功能 * id: map id */ openContextMenu (id){ var $contextmenuDiv = $('&lt;div id=&quot;contextmenu_container&quot; class=&quot;contextmenu&quot;&gt;'+ '&lt;ul&gt;'+ '&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;stopDraw&quot;&gt;停止绘制&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=&quot;#&quot; id=&quot;beginDraw&quot;&gt;开始绘制&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;' ); $(&quot;#&quot; + id).append($contextmenuDiv); var menu_overlay = new ol.Overlay({ element: document.getElementById(&quot;contextmenu_container&quot;), positioning: 'center-center' }); menu_overlay.setMap(this.map); var _this = this; $(this.map.getViewport()).on(&quot;contextmenu&quot;, function(e){ e.preventDefault(); var coordinate = _this.map.getEventCoordinate(e); menu_overlay.setPosition(coordinate); }); $(this.map.getViewport()).on(&quot;click&quot;, function(e){ e.preventDefault(); menu_overlay.setPosition(undefined); }); $(&quot;#stopDraw&quot;).on('click',function(){ _this.map.removeInteraction(_this.map.draw); if(_this.map.sourceByDraw &amp;&amp; _this.map.sourceByDraw.getFeatures().length&gt;0){ var drawGeometryPoint = JSON.stringify(_this.map.sourceByDraw.getFeatures()[0].getGeometry().getCoordinates()); //绘制的点 } menu_overlay.setPosition(undefined); }) $(&quot;#beginDraw&quot;).on('click',function(){ _this.map.addInteraction(_this.map.draw); menu_overlay.setPosition(undefined); }) } /** * 地图导出 * mapId */ showMapExportBtn (mapId){ var me = this; var $downloadPng = $('&lt;div style=&quot;position: absolute;left: 1%;top: 10%;background-color:#fff;width: 43px;height:34px;&quot; &gt;'+ '&lt;a id=&quot;export-png&quot; class=&quot;btn btn-default&quot;&gt;&lt;i class=&quot;fa fa-download fa-lg&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/div&gt;'); $(&quot;#&quot; + mapId).append($downloadPng); document.getElementById('export-png').addEventListener('click', function() { me.map.once('postcompose', function(event) { var canvas = event.context.canvas; if (navigator.msSaveBlob) { navigator.msSaveBlob(canvas.msToBlob(), 'map.png'); } else { canvas.toBlob(function(blob) { saveAs(blob, 'map.png'); }); } var image = me.up().up().up().up().down('image[name=scheduRelease]'); if(!image){ image = me.up().up().up().up().down('image[name=scheduReleaseRiver]'); } image &amp;&amp; image.setSrc(me.convertCanvasToImage(canvas).src) }); map.renderSync(); }); } // 从 canvas 提取图片 image convertCanvasToImage (canvas) { //新Image对象，可以理解为DOM var image = new Image(); // canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持 // 指定格式 PNG image.src = canvas.toDataURL(&quot;image/png&quot;); return image; } } export default Map × Search results Close "},"pointer_MouseSource.js.html":{"id":"pointer_MouseSource.js.html","title":"Source: pointer/MouseSource.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/MouseSource.js // Based on https://github.com/Polymer/PointerEvents import EventSource from './EventSource' class MouseSource extends EventSource { constructor (dispatcher) { super() let mapping = { 'mousedown': this.mousedown, 'mousemove': this.mousemove, 'mouseup': this.mouseup, 'mouseover': this.mouseover, 'mouseout': this.mouseout } /** * call */ EventSource.call(this, dispatcher, mapping) /** * @const * @type {!Object.&lt;string, Event|Object&gt;} */ this.pointerMap = dispatcher.pointerMap /** * lastTouches * @type {Array} */ this.lastTouches = [] } /** * @const * @type {number} */ static POINTER_ID = 1 /** * @const * @type {string} */ static POINTER_TYPE = 'mouse' /** * Radius around touchend that swallows mouse events. * @const * @type {number} */ static DEDUP_DIST = 25 isEventSimulatedFromTouch_ (inEvent) { let [lts, x, y] = [this.lastTouches, inEvent.clientX, inEvent.clientY] for (var i = 0, l = lts.length, t; i &lt; l &amp;&amp; (t = lts[i]); i++) { // simulated mouse events will be swallowed near a primary touchend let [dx, dy] = [Math.abs(x - t[0]), Math.abs(y - t[1])] if (dx &lt;= MouseSource.DEDUP_DIST &amp;&amp; dy &lt;= MouseSource.DEDUP_DIST) { return true } } return false } /** * Creates a copy of the original event that will be used * for the fake pointer event. * @param inEvent * @param dispatcher * @returns {Object} */ static prepareEvent = function (inEvent, dispatcher) { let e = dispatcher.cloneEvent(inEvent, inEvent) // forward mouse preventDefault let pd = e.preventDefault e.preventDefault = function () { inEvent.preventDefault() pd() } e.pointerId = MouseSource.POINTER_ID e.isPrimary = true e.pointerType = MouseSource.POINTER_TYPE return e } /** * Handler for `mousedown`. * @param {Event} inEvent The in event. */ mousedown (inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { if (MouseSource.POINTER_ID.toString() in this.pointerMap) { this.cancel(inEvent) } let e = MouseSource.prepareEvent(inEvent, this.dispatcher) this.pointerMap[MouseSource.POINTER_ID.toString()] = inEvent this.dispatcher.down(e, inEvent) } } /** * Handler for `mousemove`. * @param {Event} inEvent The in event. */ mousemove (inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { let e = MouseSource.prepareEvent(inEvent, this.dispatcher) this.dispatcher.move(e, inEvent) } } /** * Handler for `mouseup`. * @param {Event} inEvent The in event. */ mouseup (inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { let p = this.pointerMap[MouseSource.POINTER_ID.toString()] if (p &amp;&amp; p.button === inEvent.button) { let e = MouseSource.prepareEvent(inEvent, this.dispatcher) this.dispatcher.up(e, inEvent) this.cleanupMouse() } } } /** * Handler for `mouseover`. * @param {Event} inEvent The in event. */ mouseover (inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { let e = MouseSource.prepareEvent(inEvent, this.dispatcher) this.dispatcher.enterOver(e, inEvent) } } /** * Handler for `mouseout`. * @param {Event} inEvent The in event. */ mouseout (inEvent) { if (!this.isEventSimulatedFromTouch_(inEvent)) { let e = MouseSource.prepareEvent(inEvent, this.dispatcher) this.dispatcher.leaveOut(e, inEvent) } } /** * Dispatches a `pointercancel` event. * @param {Event} inEvent The in event. */ cancel (inEvent) { let e = MouseSource.prepareEvent(inEvent, this.dispatcher) this.dispatcher.cancel(e, inEvent) this.cleanupMouse() } /** * Remove the mouse from the list of active pointers. */ cleanupMouse () { delete this.pointerMap[MouseSource.POINTER_ID.toString()] } } export default MouseSource × Search results Close "},"pointer_MsSource.js.html":{"id":"pointer_MsSource.js.html","title":"Source: pointer/MsSource.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/MsSource.js // Based on https://github.com/Polymer/PointerEvents import EventSource from './EventSource' class MsSource extends EventSource { constructor (dispatcher) { super() /** * mapping * @type {{MSPointerDown: MsSource.msPointerDown, MSPointerMove: MsSource.msPointerMove, MSPointerUp: MsSource.msPointerUp, MSPointerOut: MsSource.msPointerOut, MSPointerOver: MsSource.msPointerOver, MSPointerCancel: MsSource.msPointerCancel, MSGotPointerCapture: MsSource.msGotPointerCapture, MSLostPointerCapture: MsSource.msLostPointerCapture}} */ let mapping = { 'MSPointerDown': this.msPointerDown, 'MSPointerMove': this.msPointerMove, 'MSPointerUp': this.msPointerUp, 'MSPointerOut': this.msPointerOut, 'MSPointerOver': this.msPointerOver, 'MSPointerCancel': this.msPointerCancel, 'MSGotPointerCapture': this.msGotPointerCapture, 'MSLostPointerCapture': this.msLostPointerCapture } /** * call */ EventSource.call(this, dispatcher, mapping) /** * @const * @type {!Object.&lt;string, Event|Object&gt;} */ this.pointerMap = dispatcher.pointerMap /** * @const * @type {Array.&lt;string&gt;} */ this.POINTER_TYPES = [ '', 'unavailable', 'touch', 'pen', 'mouse' ] } /** * Creates a copy of the original event that will be used * for the fake pointer event. * @param inEvent * @returns {*} * @private */ prepareEvent_ (inEvent) { let e = inEvent if (typeof inEvent.pointerType === 'number') { e = this.dispatcher.cloneEvent(inEvent, inEvent) e.pointerType = this.POINTER_TYPES[inEvent.pointerType] } return e } /** * Remove this pointer from the list of active pointers. * @param pointerId */ cleanup (pointerId) { delete this.pointerMap[pointerId.toString()] } /** * Handler for `msPointerDown`. * @param inEvent */ msPointerDown (inEvent) { this.pointerMap[inEvent.pointerId.toString()] = inEvent let e = this.prepareEvent_(inEvent) this.dispatcher.down(e, inEvent) } /** * Handler for `msPointerMove`. * @param {Event} inEvent The in event. */ msPointerMove (inEvent) { let e = this.prepareEvent_(inEvent) this.dispatcher.move(e, inEvent) } /** * Handler for `msPointerUp`. * @param {Event} inEvent The in event. */ msPointerUp (inEvent) { let e = this.prepareEvent_(inEvent) this.dispatcher.up(e, inEvent) this.cleanup(inEvent.pointerId) } /** * Handler for `msPointerOut`. * @param {Event} inEvent The in event. */ msPointerOut (inEvent) { let e = this.prepareEvent_(inEvent) this.dispatcher.leaveOut(e, inEvent) } /** * Handler for `msPointerOver`. * @param {Event} inEvent The in event. */ msPointerOver (inEvent) { let e = this.prepareEvent_(inEvent) this.dispatcher.enterOver(e, inEvent) } /** * Handler for `msPointerCancel`. * @param {Event} inEvent The in event. */ msPointerCancel (inEvent) { let e = this.prepareEvent_(inEvent) this.dispatcher.cancel(e, inEvent) this.cleanup(inEvent.pointerId) } /** * Handler for `msLostPointerCapture`. * @param {Event} inEvent The in event. */ msLostPointerCapture (inEvent) { let e = this.dispatcher.makeEvent('lostpointercapture', inEvent, inEvent) this.dispatcher.dispatchEvent(e) } /** * Handler for `msGotPointerCapture`. * @param {Event} inEvent The in event. */ msGotPointerCapture (inEvent) { let e = this.dispatcher.makeEvent('gotpointercapture', inEvent, inEvent) this.dispatcher.dispatchEvent(e) } } export default MsSource × Search results Close "},"pointer_NativeSource.js.html":{"id":"pointer_NativeSource.js.html","title":"Source: pointer/NativeSource.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/NativeSource.js // Based on https://github.com/Polymer/PointerEvents import EventSource from './EventSource' class NativeSource extends EventSource { constructor (dispatcher) { super() let mapping = { 'pointerdown': this.pointerDown, 'pointermove': this.pointerMove, 'pointerup': this.pointerUp, 'pointerout': this.pointerOut, 'pointerover': this.pointerOver, 'pointercancel': this.pointerCancel, 'gotpointercapture': this.gotPointerCapture, 'lostpointercapture': this.lostPointerCapture } /** * call */ EventSource.call(this, dispatcher, mapping) } /** * Handler for `pointerdown`. * @param {Event} inEvent The in event. */ pointerDown (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `pointermove`. * @param {Event} inEvent The in event. */ pointerMove (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `pointerup`. * @param {Event} inEvent The in event. */ pointerUp (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `pointerout`. * @param {Event} inEvent The in event. */ pointerOut (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `pointerover`. * @param {Event} inEvent The in event. */ pointerOver (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `pointercancel`. * @param {Event} inEvent The in event. */ pointerCancel (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `lostpointercapture`. * @param {Event} inEvent The in event. */ lostPointerCapture (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } /** * Handler for `gotpointercapture`. * @param {Event} inEvent The in event. */ gotPointerCapture (inEvent) { this.dispatcher.fireNativeEvent(inEvent) } } export default NativeSource × Search results Close "},"utils_observable-emit.js.html":{"id":"utils_observable-emit.js.html","title":"Source: utils/observable-emit.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: utils/observable-emit.js const Observable = function () { this.Events = {} this.__cnt = 0 } Observable.hasOwnKey = Function.call.bind(Object.hasOwnProperty) Observable.slice = Function.call.bind(Array.prototype.slice) /** * 事件分发 * @param eventName * @param callback * @param context * @returns {(*|*)[]} */ Observable.prototype.on = function (eventName, callback, context) { return (this.bindEvent(eventName, callback, 0, context)) } /** * 取消监听 * @param event * @returns {boolean} */ Observable.prototype.un = function (event) { var eventName = '' var key = '' var r = false var type = typeof event var that = this if (type === 'string') { if (Observable.hasOwnKey(this.Events, event)) { delete this.Events[event] return true } return false } else if (type === 'object') { eventName = event[0] key = event[1] if (Observable.hasOwnKey(this.Events, eventName) &amp;&amp; Observable.hasOwnKey(this.Events[eventName], key)) { delete this.Events[eventName][key] return true } return false } else if (type === 'function') { that.eachEvent(that.Events, function (keyA, itemA) { that.eachEvent(itemA, function (keyB, itemB) { if (itemB[0] === event) { delete that.Events[keyA][keyB] r = true } }) }) return r } return true } /** * 事件监听（只触发一次） * @param eventName * @param callback * @param context * @returns {(*|*)[]} */ Observable.prototype.once = function (eventName, callback, context) { return (this.bindEvent(eventName, callback, 1, context)) } /** * 响应事件 * @param eventName * @param args */ Observable.prototype.action = function (eventName, args) { if (Observable.hasOwnKey(this.Events, eventName)) { this.eachEvent(this.Events[eventName], function (key, item) { item[0].apply(item[2], args) if (item[1]) { delete this.Events[eventName][key] } }) } } /** * 实时触发响应 * @param eventName */ Observable.prototype.dispatch = function (eventName) { var that = this var args = Observable.slice(arguments, 1) setTimeout(function () { that.action(eventName, args) }) } /** * 延后触发响应 * @param eventName */ Observable.prototype.dispatchSync = function (eventName) { this.action(eventName, Observable.slice(arguments, 1)) } /** * 清空发布中心 */ Observable.prototype.clear = function () { this.Events = {} } /** * 绑定事件 * @param eventName * @param callback * @param isOne * @param context * @returns {[*,*]} */ Observable.prototype.bindEvent = function (eventName, callback, isOne, context) { if (typeof eventName !== 'string' || typeof callback !== 'function') { throw new Error('传入的事件名称和回调函数有误！') } if (!Observable.hasOwnKey(this.Events, eventName)) { this.Events[eventName] = {} } this.Events[eventName][++this.__cnt] = [callback, isOne, context] return [eventName, this.__cnt] } /** * 循环触发事件 * @param obj * @param callback */ Observable.prototype.eachEvent = function (obj, callback) { for (var key in obj) { if (Observable.hasOwnKey(obj, key)) { callback(key, obj[key]) } } } export default Observable × Search results Close "},"control_BZoomSlider.js.html":{"id":"control_BZoomSlider.js.html","title":"Source: control/BZoomSlider.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/BZoomSlider.js /** * @desc 定制缩放控制条(仿百度) */ import { ol } from '../constants' import '../asset/scss/zoomSlider.scss' import { BASE_CLASS_NAME } from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' import { EventType } from '../event/EventType' ol.control.BZoomSlider = function (params) { this.options = params || {} /** * 当前分辨率 * @type {undefined} * @private */ this.currentResolution_ = undefined /** * 滑块默认方向（默认竖向） * @type {number} * @private */ this.direction_ = ol.control.BZoomSlider.Direction_.VERTICAL /** * 是否正在拖拽 * @type {boolean} * @private */ this.dragging_ = false /** * 高度限制 * @type {number} * @private */ this.heightLimit_ = 0 /** * 宽度限制 * @type {number} * @private */ this.widthLimit_ = 0 /** * 原始X * @type {null} * @private */ this.previousX_ = null /** * 原始Y * @type {null} * @private */ this.previousY_ = null /** * 计算出的视图大小（边框加边距） * @type {null} * @private */ this.thumbSize_ = null /** * 滑块是否被初始化 * @type {boolean} * @private */ this.sliderInitialized_ = false /** * 动画过渡时延 * @type {number} * @private */ this.duration_ = this.options['duration'] !== undefined ? this.options['duration'] : 200 /** * 视图限制 * @type {{ANIMATING: number, INTERACTING: number}} */ this.viewHint = { ANIMATING: 0, INTERACTING: 1 } /** * @private * @type {number} */ this.pixelDelta_ = this.options['pixelDelta'] !== undefined ? this.options['pixelDelta'] : 128 let className = (this.options.className !== undefined ? this.options.className : 'gmap-zoom-slider') /** * @private * @type {Element} */ this.element = htmlUtils.create('div', (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) let translateContent = htmlUtils.create('div', ('gmap-zoom-slider-translate-content' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), this.element) let silderContent = htmlUtils.create('div', ('gmap-zoom-slider-content' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), this.element) let translateN = htmlUtils.create('div', ('gmap-zoom-slider-button gmap-zoom-slider-translate-n' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), translateContent) translateN.setAttribute('title', '向上平移') Events.listen(translateN, EventType.CLICK, ol.control.BZoomSlider.prototype.handletranslateClick_.bind(this, 'translateN')) let translateS = htmlUtils.create('div', ('gmap-zoom-slider-button gmap-zoom-slider-translate-s' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), translateContent) translateS.setAttribute('title', '向下平移') Events.listen(translateS, EventType.CLICK, ol.control.BZoomSlider.prototype.handletranslateClick_.bind(this, 'translateS')) let translateW = htmlUtils.create('div', ('gmap-zoom-slider-button gmap-zoom-slider-translate-w' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), translateContent) translateW.setAttribute('title', '向左平移') Events.listen(translateW, EventType.CLICK, ol.control.BZoomSlider.prototype.handletranslateClick_.bind(this, 'translateW')) let translateE = htmlUtils.create('div', ('gmap-zoom-slider-button gmap-zoom-slider-translate-e' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), translateContent) translateE.setAttribute('title', '向右平移') Events.listen(translateE, EventType.CLICK, ol.control.BZoomSlider.prototype.handletranslateClick_.bind(this, 'translateE')) let zoomIn = htmlUtils.create('div', ('gmap-zoom-slider-zoom-in' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), silderContent) zoomIn.setAttribute('title', '放大') Events.listen(zoomIn, EventType.CLICK, ol.control.BZoomSlider.prototype.handleZoomClick_.bind(this, 1)) let zoomOut = htmlUtils.create('div', ('gmap-zoom-slider-zoom-out' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), silderContent) zoomOut.setAttribute('title', '缩小') Events.listen(zoomOut, EventType.CLICK, ol.control.BZoomSlider.prototype.handleZoomClick_.bind(this, -1)) let slider = htmlUtils.create('div', ('gmap-zoom-slider-zoom-slider' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), silderContent) this.sliderBackgroundTop = htmlUtils.create('div', ('slider-background-top' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), slider) this.sliderBackgroundBottom = htmlUtils.create('div', ('slider-background-bottom' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), slider) let sliderBackgroundMask = htmlUtils.create('div', ('slider-background-mask' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), slider) sliderBackgroundMask.setAttribute('title', '缩放到此级别') this.sliderBar = htmlUtils.create('div', ('slider-bar' + ' ' + BASE_CLASS_NAME.CLASS_SELECTABLE), slider) this.sliderBar.setAttribute('title', '滑动缩放地图') /** * 滑块容器 * @type {Element} */ this.silderContent = silderContent Events.listen(this.silderContent, 'pointerdown', this.handleDraggerStart_, this) Events.listen(this.silderContent, 'pointermove', this.handleDraggerDrag_, this) Events.listen(this.silderContent, 'pointerup', this.handleDraggerEnd_, this) Events.listen(this.silderContent, EventType.CLICK, this.handleContainerClick_, this) Events.listen(this.sliderBar, EventType.CLICK, function (event) { event.stopPropagation() }) let render = this.options['render'] ? this.options['render'] : ol.control.BZoomSlider.render ol.control.Control.call(this, { element: this.element, render: render, target: this.options['target'] }) } ol.inherits(ol.control.BZoomSlider, ol.control.Control) /** * 处理缩放点击 * @param delta * @param event * @private */ ol.control.BZoomSlider.prototype.handleZoomClick_ = function (delta, event) { event.preventDefault() this.zoomByDelta_(delta) } /** * 处理平移点击事件 * @param type * @param event * @private */ ol.control.BZoomSlider.prototype.handletranslateClick_ = function (type, event) { event.preventDefault() let view = this.getMap().getView() let mapUnitsDelta = view.getResolution() * this.pixelDelta_ let [deltaX, deltaY] = [0, 0] switch (type) { case 'translateN': deltaY = mapUnitsDelta break case 'translateS': deltaY = -mapUnitsDelta break case 'translateW': deltaX = mapUnitsDelta break case 'translateE': deltaX = -mapUnitsDelta break } let delta = [deltaX, deltaY] ol.coordinate.rotate(delta, view.getRotation()) this.pan(view, delta, this.duration_) } /** * 平移地图 * @param view * @param delta * @param optDuration */ ol.control.BZoomSlider.prototype.pan = function (view, delta, optDuration) { let currentCenter = view.getCenter() if (currentCenter) { let center = view.constrainCenter( [currentCenter[0] + delta[0], currentCenter[1] + delta[1]]) if (optDuration) { view.animate({ duration: optDuration, easing: ol.easing.linear, center: center }) } else { view.setCenter(center) } } } /** * @param {number} delta Zoom delta. * @private */ ol.control.BZoomSlider.prototype.zoomByDelta_ = function (delta) { let view = this.getMap().getView() if (view &amp;&amp; view instanceof ol.View) { let currentResolution = view.getResolution() if (currentResolution) { let newResolution = view.constrainResolution(currentResolution, delta) if (this.duration_ &gt; 0) { if (view.getAnimating()) { view.cancelAnimations() } view.animate({ resolution: newResolution, duration: this.duration_, easing: ol.easing.easeOut }) } else { view.setResolution(newResolution) } } } } /** * 更新控制条element * @param {ol.MapEvent} mapEvent Map event. * @this {ol.control.BZoomSlider} * @api */ ol.control.BZoomSlider.render = function (mapEvent) { if (!mapEvent.frameState) { return } if (!this.sliderInitialized_) { this.initSlider_() } let res = mapEvent.frameState.viewState.resolution if (res !== this.currentResolution_) { this.currentResolution_ = res this.setThumbPosition_(res) } } /** * 允许的方向值 * @type {{VERTICAL: number, HORIZONTAL: number}} * @private */ ol.control.BZoomSlider.Direction_ = { VERTICAL: 0, HORIZONTAL: 1 } /** * 设置地图 * @param map */ ol.control.BZoomSlider.prototype.setMap = function (map) { if (map &amp;&amp; map instanceof ol.Map) { ol.control.Control.prototype.setMap.call(this, map) if (map) { map.render() } } else { throw Error('传入的不是地图对象！') } } /** * @inheritDoc */ ol.control.BZoomSlider.prototype.disposeInternal = function () { Events.listen(this.silderContent, 'pointercancel', function (event) {}, this) ol.control.Control.prototype.disposeInternal.call(this) } /** * 初始化滑块元素 * @private */ ol.control.BZoomSlider.prototype.initSlider_ = function () { let container = this.silderContent let containerSize = { width: container.offsetWidth, height: container.offsetHeight } let thumb = htmlUtils.getElementsByClassName('.slider-bar', container) let computedStyle = getComputedStyle(thumb) let thumbWidth = thumb.offsetWidth + parseFloat(computedStyle['marginRight']) + parseFloat(computedStyle['marginLeft']) let thumbHeight = thumb.offsetHeight + parseFloat(computedStyle['marginTop']) + parseFloat(computedStyle['marginBottom']) this.thumbSize_ = [thumbWidth, thumbHeight] if (containerSize.width &gt; containerSize.height) { this.direction_ = ol.control.BZoomSlider.Direction_.HORIZONTAL this.widthLimit_ = containerSize.width - thumbWidth } else { this.direction_ = ol.control.BZoomSlider.Direction_.VERTICAL this.heightLimit_ = containerSize.height - thumbHeight } this.sliderInitialized_ = true } /** * 容器点击事件处理 * @param event * @private */ ol.control.BZoomSlider.prototype.handleContainerClick_ = function (event) { let view = this.getMap().getView() let relativePosition = this.getRelativePosition_(event.offsetX - this.thumbSize_[0] / 2, event.offsetY - this.thumbSize_[1] / 2) let resolution = this.getResolutionForPosition_(relativePosition) view.animate({ resolution: view.constrainResolution(resolution), duration: this.duration_, easing: ol.easing.easeOut }) } /** * 处理拖拽 * @param event * @private */ ol.control.BZoomSlider.prototype.handleDraggerStart_ = function (event) { if (!this.dragging_ &amp;&amp; event.target === htmlUtils.getElementsByClassName('.slider-bar', this.silderContent)) { // this.getMap().getView().setHint(this.viewHint.INTERACTING, 1) this.previousX_ = event.clientX this.previousY_ = event.clientY this.dragging_ = true } } /** * 处理拖动事件 * @param event * @private */ ol.control.BZoomSlider.prototype.handleDraggerDrag_ = function (event) { if (this.dragging_) { let element = htmlUtils.getElementsByClassName('.slider-bar', this.silderContent) let deltaX = event.clientX - this.previousX_ + parseInt(element.style.left, 10) let deltaY = event.clientY - this.previousY_ + parseInt(element.style.top, 10) let relativePosition = this.getRelativePosition_(deltaX, deltaY) this.currentResolution_ = this.getResolutionForPosition_(relativePosition) this.getMap().getView().setResolution(this.currentResolution_) this.setThumbPosition_(this.currentResolution_) this.previousX_ = event.clientX this.previousY_ = event.clientY } } /** * 处理拖拽结束事件 * @param event * @private */ ol.control.BZoomSlider.prototype.handleDraggerEnd_ = function (event) { if (this.dragging_) { let view = this.getMap().getView() // view.setHint(ol.ViewHint.INTERACTING, -1) view.animate({ resolution: view.constrainResolution(this.currentResolution_), duration: this.duration_, easing: ol.easing.easeOut }) this.dragging_ = false this.previousX_ = undefined this.previousY_ = undefined } } /** * 计算指针位置（相对于父容器） * @param res * @private */ ol.control.BZoomSlider.prototype.setThumbPosition_ = function (res) { let position = this.getPositionForResolution_(res) let thumb = htmlUtils.getElementsByClassName('.slider-bar', this.silderContent) if (this.direction_ === ol.control.BZoomSlider.Direction_.HORIZONTAL) { thumb.style.left = this.widthLimit_ * position + 'px' this.sliderBackgroundBottom.style.width = this.widthLimit_ - (this.widthLimit_ * position - 5) + 'px' } else { thumb.style.top = this.heightLimit_ * position + 'px' this.sliderBackgroundBottom.style.height = this.heightLimit_ - (this.heightLimit_ * position - 5) + 'px' } } /** * 给出x和y偏移量的指针的相对位置 * @param x * @param y * @returns {number} * @private */ ol.control.BZoomSlider.prototype.getRelativePosition_ = function (x, y) { let amount if (this.direction_ === ol.control.BZoomSlider.Direction_.HORIZONTAL) { amount = x / this.widthLimit_ } else { amount = y / this.heightLimit_ } return Math.min(Math.max(amount, 0), 1) } /** * 计算相关分辨率 * @param position * @returns {number} * @private */ ol.control.BZoomSlider.prototype.getResolutionForPosition_ = function (position) { let view = this.getMap().getView() if (view &amp;&amp; view instanceof ol.View) { return this.getResolutionForValueFunction(1 - position) } } /** * 获取值 * @param resolution * @param optPower * @returns {number} */ ol.control.BZoomSlider.prototype.getValueForResolutionFunction = function (resolution, optPower) { let power = optPower || 2 let view = this.getMap().getView() let maxResolution = view.getMaxResolution() let minResolution = view.getMinResolution() let max = Math.log(maxResolution / minResolution) / Math.log(power) return ((Math.log(maxResolution / resolution) / Math.log(power)) / max) } /** * 获取分辨率 * @param value * @param optPower * @returns {number} */ ol.control.BZoomSlider.prototype.getResolutionForValueFunction = function (value, optPower) { let power = optPower || 2 let view = this.getMap().getView() let maxResolution = view.getMaxResolution() let minResolution = view.getMinResolution() let max = Math.log(maxResolution / minResolution) / Math.log(power) return (maxResolution / Math.pow(power, value * max)) } /** * 计算相关位置 * @param res * @returns {number} * @private */ ol.control.BZoomSlider.prototype.getPositionForResolution_ = function (res) { let view = this.getMap().getView() if (view &amp;&amp; view instanceof ol.View) { return (1 - this.getValueForResolutionFunction(res)) } } let olControlBZoomSlider = ol.control.BZoomSlider export default olControlBZoomSlider × Search results Close "},"control_compareLayer.js.html":{"id":"control_compareLayer.js.html","title":"Source: control/compareLayer.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/compareLayer.js /** * @desc 用于图层比较 */ import { ol } from '../constants' import '../asset/scss/compareLayer' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' import 'pepjs' ol.control.CompareLayer = function (beforeMap, afterMap, params) { this.options = params || {} if (beforeMap &amp;&amp; afterMap) { this.beforeMap = beforeMap this.afterMap = afterMap } else { throw new Error('图层必须传入！') } this.orderLayerZindex() this.className = (this.options.className !== undefined ? this.options.className : 'gmap-compare') /** * 当前截取位置占整个视图宽度的比例 * @type {number} */ this.initPosition = (this.options['initPosition'] !== undefined ? this.options['initPosition'] : 0.5) /** * 是否正在拖拽 * @type {boolean} * @private */ this.dragging_ = false /** * 原始X * @type {null} * @private */ this.previousX_ = null /** * 原始Y * @type {null} * @private */ this.previousY_ = null /** * @private * @type {Element} */ this.element_ = htmlUtils.create('div', (this.className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) /** * @private * @type {Element} */ let innerElement_ = htmlUtils.create('div', this.className + '-inner', this.element_) Events.listen(innerElement_, 'pointerdown', this.handleDraggerStart_, this) Events.listen(innerElement_, 'pointermove', this.handleDraggerDrag_, this) Events.listen(innerElement_, 'pointerup', this.handleDraggerEnd_, this) Events.listen(window, 'pointerup', this.handleDraggerEnd_, this) ol.control.Control.call(this, { element: this.element_, target: this.options['target'] }) } ol.inherits(ol.control.CompareLayer, ol.control.Control) /** * setup */ ol.control.CompareLayer.prototype.initControl = function () { /** * 获取当前视图大小 * @type {ClientRect} * @private */ this._bounds = this.getMap().getTargetElement().getBoundingClientRect() this.percent = 0.5 this._setPosition(this._bounds.width, this._bounds.width / 2) this.resize() this.clipLayer() } /** * 处理拖拽 * @param event * @private */ ol.control.CompareLayer.prototype.handleDraggerStart_ = function (event) { if (!this.dragging_ &amp;&amp; event.target === htmlUtils.getElementsByClassName('.' + this.className + '-inner', this.element_)) { this.previousX_ = event.clientX this.previousY_ = event.clientY this.dragging_ = true } } /** * 处理拖动事件 * @param event * @private */ ol.control.CompareLayer.prototype.handleDraggerDrag_ = function (event) { if (this.dragging_) { this._bounds = this.getMap().getTargetElement().getBoundingClientRect() this._setPosition(this._bounds.width, this._getX(event)) this.previousX_ = event.clientX this.previousY_ = event.clientY } } /** * 处理拖拽结束事件 * @param event * @private */ ol.control.CompareLayer.prototype.handleDraggerEnd_ = function (event) { if (this.dragging_) { this.dragging_ = false this.previousX_ = undefined this.previousY_ = undefined } } /** * 通过canvas切割视图 */ ol.control.CompareLayer.prototype.clipLayer = function () { let that = this this.getMap().un('precompose', this.precompose) this.getMap().un('postcompose', this.postcompose) this.precompose = this.beforeMap.on('precompose', event =&gt; { let ctx = event.context let width = ctx.canvas.width * (that.initPosition) ctx.save() ctx.beginPath() ctx.rect(width, 0, ctx.canvas.width - width, ctx.canvas.height) ctx.clip() }) this.postcompose = this.beforeMap.on('postcompose', event =&gt; { let ctx = event.context ctx.restore() }) } /** * 设置切割位置 * @param sourceWidth * @param value * @private */ ol.control.CompareLayer.prototype._setPosition = function (sourceWidth, value) { let pos = 'translate(' + value + 'px, 0)' this.element_.style.transform = pos this.element_.style.WebkitTransform = pos this._x = value this.percent = value / sourceWidth this.initPosition = value / sourceWidth this.getMap().render() } /** * 窗口变化事件 */ ol.control.CompareLayer.prototype.resize = function () { let resizeEvt = (('orientationchange' in window) ? 'orientationchange' : 'resize') let doc = window.document let that = this window.addEventListener(resizeEvt, function () { setTimeout(function () { that._bounds = that.getMap().getTargetElement().getBoundingClientRect() that._setPosition(that._bounds.width, that._bounds.width * that.percent) }, 50) }, false) window.addEventListener('pageshow', function (e) { if (e.persisted) { setTimeout(function () { that._bounds = that.getMap().getTargetElement().getBoundingClientRect() that._setPosition(that._bounds.width, that._bounds.width * that.percent) }, 50) } }, false) if (doc.readyState === 'complete') { setTimeout(function () { that._bounds = that.getMap().getTargetElement().getBoundingClientRect() that._setPosition(that._bounds.width, that._bounds.width * that.percent) }, 50) } else { doc.addEventListener('DOMContentLoaded', function (e) { setTimeout(function () { that._bounds = that.getMap().getTargetElement().getBoundingClientRect() that._setPosition(that._bounds.width, that._bounds.width * that.percent) }, 50) }, false) } } /** * 获取当前位置 * @param e * @returns {number} * @private */ ol.control.CompareLayer.prototype._getX = function (e) { e = e.touches ? e.touches[0] : e let x = e.clientX - this._bounds.left if (x &lt; 0) x = 0 if (x &gt; this._bounds.width) x = this._bounds.width return x } /** * 设置地图 * @param map */ ol.control.CompareLayer.prototype.setMap = function (map) { if (map &amp;&amp; map instanceof ol.Map) { ol.control.Control.prototype.setMap.call(this, map) if (map) { map.render() this.initControl() } } else { throw Error('传入的不是地图对象！') } } /** * 设置上一级图层 * @param beforeMap */ ol.control.CompareLayer.prototype.setBeforeLayet = function (beforeMap) { if (beforeMap) { this.beforeMap = beforeMap this.orderLayerZindex() } else { throw Error('设置图层错误！') } } /** * 设置下一级图层 * @param afterMap */ ol.control.CompareLayer.prototype.setAfterLayer = function (afterMap) { if (afterMap) { this.afterMap = afterMap this.orderLayerZindex() } else { throw Error('设置图层错误！') } } /** * 调整相关图层层级，避免图层压盖 */ ol.control.CompareLayer.prototype.orderLayerZindex = function () { if (this.afterMap &amp;&amp; this.beforeMap) { let afterMapIndex = this.afterMap.getZIndex() let beforeMapIndex = this.beforeMap.getZIndex() let max = Math.max(afterMapIndex, beforeMapIndex) let min = Math.min(afterMapIndex, beforeMapIndex) if (max === min) { max = max + 1 } this.beforeMap.setZIndex(max) this.afterMap.setZIndex(min) } } let olControlCompareLayer = ol.control.CompareLayer export default olControlCompareLayer × Search results Close "},"control_contextMenu.js.html":{"id":"control_contextMenu.js.html","title":"Source: control/contextMenu.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/contextMenu.js /** * @desc 右键功能(迁移自项目扩展) */ import { ol } from '../constants' import '../asset/scss/contextMenu.scss' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' import Observable from '../utils/observable-emit' import mixin from '../utils/mixin' import cloneDeep from 'lodash/cloneDeep' ol.control.ContextMenu = function (params = {}) { this.options = params /** * 地图容器 * @type {null} */ this.mapContent = null /** * 鼠标右键的位置 * @type {Array} */ this.pixel = [] /** * width * @type {number} */ this.itemWidth = (typeof this.options['itemWidth'] === 'number' ? this.options['itemWidth'] : 160) /** * height * @type {number} */ this.itemHeight = (typeof this.options['itemHeight'] === 'number' ? this.options['itemHeight'] : 30) /** * className * @type {string} */ this.className_ = (this.options.className !== undefined ? this.options.className : 'gmap-context-menu-content') /** * @private * @type {Element} */ this.element_ = htmlUtils.create('div', (this.className_ + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) this.element_.style.display = 'none' ol.control.Control.call(this, { element: this.element_, target: this.options['target'] }) Observable.call(this) } ol.inherits(ol.control.ContextMenu, ol.control.Control) mixin(ol.control.ContextMenu, Observable) /** * 初始化dom * @param items */ ol.control.ContextMenu.prototype.initDomInternal = function (items) { this.htmlUtils(items, '', this.element_) if (this.getMap()) { this.mapContent = this.getMap().getViewport() Events.listen(this.mapContent, 'contextmenu', this.mouseDownHandle_, this) } } /** * 初始化事件 * @param event * @private */ ol.control.ContextMenu.prototype.mouseDownHandle_ = function (event) { let that = this event.stopPropagation() event.preventDefault() if (event.button === 2) { that.pixel = this.getMap().getEventPixel(event) this.dispatch('before-show', event) window.setTimeout(() =&gt; { that.show(that.pixel) that.dispatch('show', event) }, 50) } Events.listen(event.target, 'mousedown', function () { that.hide() that.dispatch('hide', event) }, this, true) } /** * showMenu * @param position */ ol.control.ContextMenu.prototype.show = function (position) { this.element_.style.display = 'block' this.element_.style.top = position[1] + 'px' this.element_.style.left = position[0] + 'px' let aDoc = this.getMap().getSize() let maxWidth = aDoc[0] - this.element_.offsetWidth let maxHeight = aDoc[1] - this.element_.offsetHeight if (this.element_.offsetTop &gt; maxHeight) { this.element_.style.top = maxHeight + 'px' } if (this.element_.offsetLeft &gt; maxWidth) { this.element_.style.left = maxWidth + 'px' } } /** * hideMenu */ ol.control.ContextMenu.prototype.hide = function () { this.element_.style.display = 'none' this.pixel = [] } /** * html处理工具 * @param items * @param index * @param content * @param isOffset * @returns {*} */ ol.control.ContextMenu.prototype.htmlUtils = function (items, index, content, isOffset) { let that = this let ulList = null if (items &amp;&amp; Array.isArray(items) &amp;&amp; items.length &gt; 0) { ulList = htmlUtils.create('ul', this.className_ + '-ul' + index + '-inner', content, this.className_ + '-ul' + index + '-inner') if (isOffset) { ulList.style.position = 'absolute' ulList.style.top = '0px' ulList.style.left = this.itemWidth + 20 + 'px' } items.forEach((item, index_) =&gt; { if (item &amp;&amp; item['name'] &amp;&amp; item['alias']) { let numList = index + '-' + index_ let li_ = htmlUtils.create('li', this.className_ + '-li-' + numList + '-inner', ulList, this.className_ + '-li-' + numList + '-inner') li_.style.width = this.itemWidth + 'px' li_.style.height = this.itemHeight + 'px' li_.style.lineHeight = this.itemHeight + 'px' li_.setAttribute('data-name', item['alias']) Events.listen(li_, 'click', function (event) { that.handleItemClick_(event, item) }, this) if (item['icon']) { let span_ = htmlUtils.create('span', 'li-icon-content', li_) if (item['iconType'] === 'iconfont') { let fontName = item['fontName'] ? item['fontName'] : 'iconfont' htmlUtils.addClass(span_, fontName + ' ' + item['icon']) if (item['iconColor']) { span_.style.color = item['iconColor'] } } else { span_.style.background = 'url(' + item['icon'] + ') 0px 0px no-repeat' } } let name_ = htmlUtils.create('span', 'li-name-content', li_) name_.innerHTML = item['name'] if (item['showLine']) { li_.style.borderBottom = '1px solid #CCCCCC' } if (item['items']) { this.htmlUtils(item['items'], numList, li_, true) Events.listen(li_, 'mouseenter', this.handleItemMouseOver_, this) Events.listen(li_, 'mouseleave', this.handleItemMouseOut_, this) } } }) } return ulList } /** * 更新面板元素 * @param type * @param item * @param items * @private */ ol.control.ContextMenu.prototype.updateElement_ = function (type, item, items) { let child_ = htmlUtils.get(this.className_ + '-ul' + '-inner') let cloneItems = cloneDeep(this.options['items']) let afterItems = null switch (type) { case 'pop': // 移除最后一个 this.element_.removeChild(child_) afterItems = cloneItems.pop() this.htmlUtils(cloneItems, '', this.element_) break case 'push': // 数组的末尾添加新的元素 this.element_.removeChild(child_) afterItems = cloneItems = cloneItems.push(item) this.htmlUtils(cloneItems, '', this.element_) break case 'shift': // 删除数组的第一个元素 this.element_.removeChild(child_) afterItems = cloneItems.shift() this.htmlUtils(cloneItems, '', this.element_) break case 'unshift': // 在数组的开头添加新元素 this.element_.removeChild(child_) afterItems = cloneItems = cloneItems.unshift(item) this.htmlUtils(cloneItems, '', this.element_) break case 'reverse': this.element_.removeChild(child_) afterItems = cloneItems.reverse() this.htmlUtils(cloneItems, '', this.element_) break default: this.element_.removeChild(child_) afterItems = items this.htmlUtils(items, '', this.element_) } return afterItems } /** * 获取鼠标右键位置的像素坐标 * @returns {ol.Pixel|*|Array} */ ol.control.ContextMenu.prototype.getCurrentPixel = function () { return this.pixel } /** * 获取鼠标点击位置的地图坐标 * @returns {ol.Coordinate} */ ol.control.ContextMenu.prototype.getCurrentCoordinates = function () { return (this.getMap().getCoordinateFromPixel(this.getCurrentPixel())) } /** * 处理列表点击事件 * @param event * @param item * @private */ ol.control.ContextMenu.prototype.handleItemClick_ = function (event, item) { if (item &amp;&amp; item['callback'] &amp;&amp; typeof item['callback'] === 'function') { item['callback'](event, { source: item, pixel: this.getCurrentPixel(), coordinates: this.getCurrentCoordinates() }) } this.dispatch('item-click', event, { source: item, pixel: this.getCurrentPixel(), coordinates: this.getCurrentCoordinates() }) window.setTimeout(() =&gt; { this.hide() }, 50) } /** * 处理鼠标移入事件 * @param event * @private */ ol.control.ContextMenu.prototype.handleItemMouseOver_ = function (event) { if (event.target &amp;&amp; event.target.childNodes) { let elements = Array.prototype.slice.call(event.target.childNodes, 0) if (elements &amp;&amp; elements.length &gt; 0) { elements.every(ele =&gt; { if (ele &amp;&amp; ele.nodeName.toLowerCase() === 'ul') { ele.style.display = 'block' return false } else { return true } }) } } } /** * 处理鼠标移出事件 * @param event * @private */ ol.control.ContextMenu.prototype.handleItemMouseOut_ = function (event) { if (event.target &amp;&amp; event.target.childNodes) { let elements = Array.prototype.slice.call(event.target.childNodes, 0) if (elements &amp;&amp; elements.length &gt; 0) { elements.every(ele =&gt; { if (ele &amp;&amp; ele.nodeName.toLowerCase() === 'ul') { ele.style.display = 'none' return false } else { return true } }) } } } /** * setMap * @param map */ ol.control.ContextMenu.prototype.setMap = function (map) { ol.control.Control.prototype.setMap.call(this, map) if (map &amp;&amp; map instanceof ol.Map) { this.initDomInternal(this.options['items']) } } /** * 移除菜单最后一项 */ ol.control.ContextMenu.prototype.pop = function () { return this.updateElement_('pop') } /** * 向菜单末尾添加一项 * @param item */ ol.control.ContextMenu.prototype.push = function (item) { if (item &amp;&amp; typeof item === 'object') { return this.updateElement_('push', item) } else { throw new Error('传入的不是对象') } } /** * 移除菜单第一项 */ ol.control.ContextMenu.prototype.shift = function () { return this.updateElement_('shift') } /** * 倒叙菜单 */ ol.control.ContextMenu.prototype.reverse = function () { return this.updateElement_('reverse') } /** * 向菜单开头添加一项 * @param item */ ol.control.ContextMenu.prototype.unshift = function (item) { if (item &amp;&amp; typeof item === 'object') { return this.updateElement_('unshift', item) } else { throw new Error('传入的不是对象') } } /** * 更新菜单 * @param items */ ol.control.ContextMenu.prototype.update = function (items) { if (items &amp;&amp; Array.isArray(items) &amp;&amp; items.length &gt; 0) { this.updateElement_('', '', items) } else { throw new Error('传入的数组有误！') } } /** * 更新内置配置 * @param items */ ol.control.ContextMenu.prototype.updateOption = function (items) { if (items &amp;&amp; Array.isArray(items) &amp;&amp; items.length &gt; 0) { this.options['items'] = items this.updateElement_('', '', items) } else { throw new Error('传入的数组有误！') } } let olControlContextMenu = ol.control.ContextMenu export default olControlContextMenu × Search results Close "},"control_FullScreen.js.html":{"id":"control_FullScreen.js.html","title":"Source: control/FullScreen.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/FullScreen.js /** * @desc 全屏控制 */ import { ol } from '../constants' import '../asset/scss/fullScreen.scss' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' import {EventType} from '../event/EventType' import screenfull from 'screenfull' ol.control.FullScreenMenu = function (params = {}) { let options = params /** * 基础类名 * @type {string} */ let className = options.className !== undefined ? options.className : 'gmap-control-full-screen' this.label = options.label !== undefined ? options.label : '\\u2922' this.labelActive = options.labelActive !== undefined ? options.labelActive : '\\u00d7' /** * 快捷键 * @private * @type {boolean} */ this.keys_ = options.keys !== undefined ? options.keys : false /** * 图标大小 * @type {[*]} * @private */ this.size_ = options.size !== undefined ? options.size : [16, 16] /** * 要放大的容器 */ this.source_ = options.source /** * delta */ this.element_ = this.initDomInternal_(className) ol.control.Control.call(this, { element: this.element_, target: options.target }) } ol.inherits(ol.control.FullScreenMenu, ol.control.Control) /** * 处理点击事件 * @param event * @private */ ol.control.FullScreenMenu.prototype.handleClick_ = function (event) { event.preventDefault() let map = this.getMap() if (map) { let element = null if (this.source_) { element = typeof this.source_ === 'string' ? document.getElementById(this.source_) : this.source_ } else { element = this.getMap().getTargetElement() } if (screenfull.enabled) { screenfull.toggle(element) screenfull.on('change', () =&gt; { if (screenfull.isFullscreen) { this.element_.firstElementChild.innerHTML = this.labelActive } else { this.element_.firstElementChild.innerHTML = this.label } }) } } } /** * 初始化相关dom * @param className * @param delta * @returns {Element} * @private */ ol.control.FullScreenMenu.prototype.initDomInternal_ = function (className) { let element = htmlUtils.create('div', (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) let inner = htmlUtils.create('span', className + '-inner', element) inner.setAttribute('title', '放大') inner.innerHTML = this.label Events.listen(element, EventType.CLICK, this.handleClick_, this) return element } let olControlFullScreenMenu = ol.control.FullScreenMenu export default olControlFullScreenMenu × Search results Close "},"control_LayerSwitcher.js.html":{"id":"control_LayerSwitcher.js.html","title":"Source: control/LayerSwitcher.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/LayerSwitcher.js /** * @ 图层切换功能控件 */ import { ol } from '../constants' import '../asset/scss/layerSwitcher.scss' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' import olLayerLayerUtils from '../utils/layerUtils' import mixin from '../utils/mixinfn' ol.control.LayerSwitcher = function (params = {}) { this.options = params /** * className * @type {string} */ this.className_ = (this.options.className !== undefined ? this.options.className : 'gmap-layer-switcher') /** * width * @type {number} */ this.options['itemWidth'] = (this.options['itemWidth'] === 'number' ? this.options['itemWidth'] : 86) /** * 底图集合 * @type {Array} * @private */ this.baseLayers_ = [] /** * 标注图层 * @type {Array} * @private */ this.labelLayers_ = [] /** * 用于标识底图的关键字 * @type {string} */ this.baseLayerKey = this.options['baseLayerKey'] ? this.options['baseLayerKey'] : 'isBaseLayer' /** * 用于标识当前底图的关键字 * @type {string} */ this.isDefaultKey = this.options['isDefaultKey'] ? this.options['isDefaultKey'] : 'isDefault' /** * 关联图层关键字 * @type {string} */ this.labelAliasKey = this.options['labelAlias'] ? this.options['labelAlias'] : 'layerName' /** * 标准labelLayer关键字 * @type {string} */ this.labelLayerKey = this.options['labelLayerKey'] ? this.options['labelLayerKey'] : 'isLabelLayer' /** * 是否已经默认执行选中操作 * @type {boolean} * @private */ this.isActionSelected_ = false /** * 是否每次操作之前强制更新图层，这在底图可能发生变化时比较有用。 */ this.forcedUpdate = this.options['forcedUpdate'] /** * height * @type {number} */ this.options['itemHeight'] = (typeof this.options['itemHeight'] === 'number' ? this.options['itemHeight'] : 60) /** * 图层关键字 * @type {string} */ this.options['key'] = (this.options['key'] ? this.options['key'] : 'layerName') if (this.labelLayerKey === this.baseLayerKey) { throw new Error('标注图层关键字不能和底图相同！') } /** * @private * @type {Element} */ this.element_ = htmlUtils.create('div', (this.className_ + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) Events.listen(this.element_, 'mouseover', this.contentMouseOver_, this) Events.listen(this.element_, 'mouseout', this.contentMouseOut_, this) /** * @private * @type {Element} */ this.innerElement_ = htmlUtils.create('ul', this.className_ + '-ul-inner', this.element_, this.className_ + '-ul-inner') if (this.options['layers'] &amp;&amp; Array.isArray(this.options['layers']) &amp;&amp; this.options['layers'].length &gt; 0) { this.initDomInternal(this.options['layers'], this.className_, this.options['key']) } else { this.element_.style.display = 'none' } ol.control.Control.call(this, { element: this.element_, target: this.options['target'] }) } ol.inherits(ol.control.LayerSwitcher, ol.control.Control) mixin(ol.control.LayerSwitcher, olLayerLayerUtils) /** * 初始化dom * @param layers * @param className * @param key */ ol.control.LayerSwitcher.prototype.initDomInternal = function (layers, className, key) { let width = this.options['itemWidth'] let height = this.options['itemHeight'] let length = layers.length this.innerElement_.style.width = width + (length - 1) * 10 + 'px' this.innerElement_.style.height = height + 'px' layers.forEach((item, index) =&gt; { if (item &amp;&amp; item[key]) { let li_ = htmlUtils.create('li', className + '-li-inner', this.innerElement_, className + '-li' + index + '-inner') li_.style.background = 'url(' + item['icon'] + ') 0px 0px no-repeat' li_.style.width = width + 'px' li_.style.height = height + 'px' li_.style.zIndex = index + 1 li_.style.right = '0px' li_.style.marginRight = (length - 1 - index) * 10 + 'px' li_.setAttribute('data-name', item[key]) Events.listen(li_, 'click', this.handleClick_, this) if (item['name']) { let name_ = htmlUtils.create('span', 'layer-name', li_) name_.setAttribute('data-name', item[key]) name_.innerHTML = item['name'] } if (!this.isActionSelected_) { if (item[this.isDefaultKey]) { htmlUtils.addClass(li_, 'selected-item') this.isActionSelected_ = true } } if (!this.isActionSelected_ &amp;&amp; (index === length - 1)) { htmlUtils.addClass(li_, 'selected-item') this.isActionSelected_ = true } } }) } /** * 鼠标移入 * @param event * @private */ ol.control.LayerSwitcher.prototype.contentMouseOver_ = function (event) { let length = this.options['layers'].length if (length &gt; 0) { for (let i = 0; i &lt; length - 1; i++) { let item = htmlUtils.get(this.className_ + '-li' + i + '-inner') if (item) { item.style.marginRight = '0px' item.style.zIndex = '' item.style.right = (length - 1 - i) * (10 + this.options['itemWidth']) + 'px' } } this.innerElement_.style.width = this.options['itemWidth'] * length + 10 * (length - 1) + 'px' } } /** * 鼠标移出 * @param event * @private */ ol.control.LayerSwitcher.prototype.contentMouseOut_ = function (event) { let length = this.options['layers'].length if (length &gt; 0) { for (let i = 0; i &lt; length - 1; i++) { let item = htmlUtils.get(this.className_ + '-li' + i + '-inner') if (item) { item.style.zIndex = i + 1 item.style.right = '0px' item.style.marginRight = (length - 1 - i) * 10 + 'px' } } this.innerElement_.style.width = this.options['itemWidth'] + (length - 1) * 10 + 'px' } } /** * 处理点击切换事件 * @param event * @private */ ol.control.LayerSwitcher.prototype.handleClick_ = function (event) { let value = event.target.getAttribute('data-name') this.switcher(this.options['key'], value) } /** * 更新底图和标准层 * @private */ ol.control.LayerSwitcher.prototype.updateBaseLayer_ = function () { if (!this.map) return this.baseLayers_ = this.getLayersArrayByKeyValue(this.baseLayerKey, true) this.labelLayers_ = this.getLayersArrayByKeyValue(this.labelLayerKey, true) if (this.baseLayers_ &amp;&amp; this.baseLayers_.length &gt; 0) { this.baseLayers_.filter(_item =&gt; { return !!_item }) } if (this.labelLayers_ &amp;&amp; this.labelLayers_.length &gt; 0) { this.labelLayers_.filter(_item =&gt; { return !!_item }) } } /** * 切换底图 * @param key * @param value */ ol.control.LayerSwitcher.prototype.switcher = function (key, value) { if (this.forcedUpdate) { this.updateBaseLayer_() } console.log( key) console.log( this.baseLayers_) if (this.baseLayers_.length &gt; 0 &amp;&amp; this.baseLayers_.length === this.options['layers'].length) { this.baseLayers_.forEach(layer =&gt; { if (layer &amp;&amp; layer.get(key) === value) { layer.setVisible(true) layer.set(this.isDefaultKey, true) } else { layer.setVisible(false) layer.set(this.isDefaultKey, false) } }) let length = this.options['layers'].length if (length &gt; 0) { for (let i = 0; i &lt; length; i++) { let item = htmlUtils.get(this.className_ + '-li' + i + '-inner') if (item &amp;&amp; item.getAttribute('data-name') === value) { htmlUtils.addClass(item, 'selected-item') } else { htmlUtils.removeClass(item, 'selected-item') } } } } else { throw new Error('请检查是否存在底图获取底图数量是否和配置相同！') } } /** * setMap * @param map */ ol.control.LayerSwitcher.prototype.setMap = function (map) { ol.control.Control.prototype.setMap.call(this, map) this.map = map if (map &amp;&amp; map instanceof ol.Map) { this.updateBaseLayer_() } } let olControlLayerSwitcher = ol.control.LayerSwitcher export default olControlLayerSwitcher × Search results Close "},"control_Loading.js.html":{"id":"control_Loading.js.html","title":"Source: control/Loading.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/Loading.js /** * @desc 全局地图加载loading */ import { ol } from '../constants' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import '../asset/scss/loading.scss' ol.control.Loading = function (params) { /** * 当前配置 * @type {*} */ this.options = params || {} /** * 地图事件 * @type {Array} */ this.mapListeners = [] /** * 切片事件 * @type {Array} */ this.tileListeners = [] /** * 加载状态 * @type {boolean} * @private */ this.loadStatus_ = false /** * 是否第一次渲染 * @type {boolean} */ this.isFirstRander = true /** * 加载进度 * @type {[*]} * @private */ this.loadProgress_ = [0, 1] // 窗口挂件类型（现有支持gif和进度条） if (this.options['widget']) { if (['animatedGif', 'progressBar'].indexOf(this.options['widget']) === -1) { throw Error('不支持的挂件类型') } else { this.widget = (this.options['widget'] ? this.options['widget'] : 'animatedGif') } } // 进度条模式 if (this.options['progressMode']) { if (['tile', 'layer'].indexOf(this.options['progressMode']) === -1) { throw Error('不支持的进度条模式') } this.loadProgressByTile_ = ((this.options['progressMode'] === 'layer') ? !(this.options['progressMode'] === 'layer') : true) } // 是否显示loading面板 this.showPanel = (typeof this.options['showPanel'] === 'boolean') ? this.options['showPanel'] : true let className = (this.options.className !== undefined ? this.options.className : 'gmap-loading-panel') // DOM let elementDom = (this.widget === 'animatedGif') ? 'span' : 'progress' let element = htmlUtils.create(elementDom, (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) if (this.widget === 'progressBar') { // element progress bar for old browsers let div = htmlUtils.create('div', 'gmap-progress-bar') htmlUtils.create('span', '', div) } this.onCustomStart = (this.options['onStart'] ? this.options['onStart'] : false) this.onCustomProgress = (this.options['onProgress'] ? this.options['onProgress'] : false) this.onCustomEnd = (this.options['onEnd'] ? this.options['onEnd'] : false) ol.control.Control.call(this, { element: element, target: this.options['target'] }) } ol.inherits(ol.control.Loading, ol.control.Control) /** * 设置 */ ol.control.Loading.prototype.setup = function () { this.setDomPosition() this.resize() let pointerDown = this.getMap().on('pointerdown', () =&gt; { this.hide() }) let beforeRander = this.getMap().on('precompose', () =&gt; { if (this.isFirstRander) { this.isFirstRander = false this.registerLayersLoadEvents_() this.show() if (this.onCustomStart) { let args = [] this.onCustomStart.apply(this, args) } } }) let afterRander = this.getMap().on('postrender', () =&gt; { this.updateLoadStatus_() if (this.loadStatus_) { if (this.onCustomEnd) { let args = [] this.onCustomEnd.apply(this, args) } this.hide() } }) this.mapListeners.push(pointerDown) this.mapListeners.push(beforeRander) this.mapListeners.push(afterRander) } /** * 设置dom位置 */ ol.control.Loading.prototype.setDomPosition = function () { let size = this.getMap().getSize() let domSize = [this.element.clientWidth, this.element.clientHeight] this.element.style.left = String(Math.round((size[0] - domSize[0]) / 2)) + 'px' this.element.style.bottom = String(Math.round((size[1] - domSize[1]) / 2)) + 'px' } /** * 窗口变化事件 */ ol.control.Loading.prototype.resize = function () { let resizeEvt = (('orientationchange' in window) ? 'orientationchange' : 'resize') let doc = window.document let that = this window.addEventListener(resizeEvt, function () { setTimeout(function () { that.setDomPosition() }, 50) }, false) window.addEventListener('pageshow', function (e) { if (e.persisted) { setTimeout(function () { that.setDomPosition() }, 50) } }, false) if (doc.readyState === 'complete') { setTimeout(function () { that.setDomPosition() }, 50) } else { doc.addEventListener('DOMContentLoaded', function (e) { setTimeout(function () { that.setDomPosition() }, 50) }, false) } } /** * 获取进度 * @param source * @returns {boolean} * @private */ ol.control.Loading.prototype.updateSourceLoadStatus_ = function (source) { return (Math.round(source.loaded / source.loading * 100) === 100) } /** * 注册图层事件 * @param layer * @private */ ol.control.Loading.prototype.registerLayerLoadEvents_ = function (layer) { let that = this layer.getSource().on('tileloadstart', function (event) { if (that.loadStatus_) { that.loadStatus_ = false that.loadProgress_ = [0, 1] if (that.widget === 'progressBar') { that.element.value = that.loadProgress_[0] that.element.max = that.loadProgress_[1] } that.show() if (that.onCustomStart) { let args = [] that.onCustomStart.apply(that, args) } } this.loading = (this.loading) ? this.loading + 1 : 1 this.isLoaded = that.updateSourceLoadStatus_(this) if (that.loadProgressByTile_) { this.loadProgress_[1] += 1 if (this.widget === 'progressBar') { that.element.max = that.loadProgress_[1] let progressBarDiv = that.element.getElementsByClassName('gmap-progress-bar') if (progressBarDiv.length &gt; 0) progressBarDiv[0].children()[0].width = String(parseInt(100 * that.progress(), 0)) + '%' } } }) layer.getSource().on(['tileloadend', 'tileloaderror'], function (e) { if (e.tile.getState() === 3) { console.warn('Loading tile failed for resource \\'' + e.tile.src_ + '\\'') } this.loaded = (this.loaded) ? this.loaded + 1 : 1 this.isLoaded = that.updateSourceLoadStatus_(this) if (that.loadProgressByTile_) { that.loadProgress_[0] += 1 if (that.widget === 'progressBar') { that.element.value = that.loadProgress_[0] let progressBarDiv = this.element.getElementsByClassName('gmap-progress-bar') if (progressBarDiv.length &gt; 0) { progressBarDiv[0].children()[0].width = String(parseInt(100 * that.progress(), 0)) + '%' } } if (that.onCustomProgress) { that.onCustomProgress.apply(that, that.loadProgress_) } } }) } /** * 注册全局图层事件 * @private */ ol.control.Loading.prototype.registerLayersLoadEvents_ = function () { let groups = this.getMap().getLayers().getArray() for (let i = 0; i &lt; groups.length; i++) { let layer = groups[i] if (layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() for (let j = 0; j &lt; layers.length; j++) { let l = layers[j] if (!(l instanceof ol.layer.Vector)) { this.tileListeners.push(this.registerLayerLoadEvents_(l)) } } } else if (layer instanceof ol.layer.Layer) { if (!(layer instanceof ol.layer.Vector)) { this.tileListeners.push(this.registerLayerLoadEvents_(layer)) } } } } /** * 更新加载状态 * @private */ ol.control.Loading.prototype.updateLoadStatus_ = function () { let loadStatusArray = [] let groups = this.getMap().getLayers().getArray() for (let i = 0; i &lt; groups.length; i++) { let layer = groups[i] if (layer) { if (layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() for (let j = 0; j &lt; layers.length; j++) { let l = layers[j] if (l &amp;&amp; l.getSource() &amp;&amp; !(l instanceof ol.layer.Vector) &amp;&amp; l.getSource().hasOwnProperty('isLoaded')) { loadStatusArray.push(l.getSource().isLoaded) } } } else if (layer.getSource() &amp;&amp; layer.getSource().hasOwnProperty('isLoaded')) { loadStatusArray.push(layer.getSource().isLoaded) } } } this.loadStatus_ = (loadStatusArray.indexOf(false) === -1) &amp;&amp; (loadStatusArray.indexOf(true) !== -1) if (!this.loadProgressByTile_) { // progress let count = {} loadStatusArray.forEach(function (i) { count[i] = (count[i] || 0) + 1 }) let loaded = (count[true]) ? count[true] : 0 // progress events if (loaded &gt; this.loadProgress_[0]) { this.loadProgress_ = [loaded, loadStatusArray.length] if (this.widget === 'progressBar') { this.element.max = this.loadProgress_[1] this.element.value = this.loadProgress_[0] } if (this.onCustomProgress) this.onCustomProgress.apply(this, this.loadProgress_) } } } /** * show */ ol.control.Loading.prototype.show = function () { if (this.showPanel) { this.element.style.display = 'block' } } /** * hide */ ol.control.Loading.prototype.hide = function () { if (this.showPanel) { this.element.style.display = 'none' } } /** * 显示进度详情 * @returns {*[]|Array|[*,*]|[number,number]} */ ol.control.Loading.prototype.progressDetails = function () { return this.loadProgress_ } /** * 显示进度条 * @returns {number} */ ol.control.Loading.prototype.progress = function () { return this.loadProgress_[0] / this.loadProgress_[1] } /** * 设置地图 * @param map */ ol.control.Loading.prototype.setMap = function (map) { if (this.mapListeners &amp;&amp; this.mapListeners.length &gt; 0) { this.mapListeners.forEach(listener =&gt; { this.getMap().unByKey(listener) }) } this.mapListeners.length = 0 ol.control.Control.prototype.setMap.call(this, map) if (map) { this.setup() } } let olControlLoading = ol.control.Loading export default olControlLoading × Search results Close "},"control_MousePosition.js.html":{"id":"control_MousePosition.js.html","title":"Source: control/MousePosition.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/MousePosition.js /** * @desc 坐标实时拾取 */ import { ol } from '../constants' import '../asset/scss/mousePosition.scss' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' ol.control.MousePositionH = function (options = {}) { this.className_ = options.className !== undefined ? options.className : 'gmap-mouse-position' let element = htmlUtils.create('div', (this.className_ + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) let render = options.render ? options.render : ol.control.MousePositionH.render ol.control.Control.call(this, { element: element, render: render, target: options.target }) Events.listen(this, 'change:' + ol.control.MousePositionH.Property_.PROJECTION, this.handleProjectionChanged_, this) if (options.coordinateFormat) { this.setCoordinateFormat(options.coordinateFormat) } if (options.projection) { this.setProjection(options.projection) } if (options.units) { this.setUnits(options.units) } /** * @private * @type {string} */ this.undefinedHTML_ = options.undefinedHTML !== undefined ? options.undefinedHTML : '' /** * @private * @type {string} */ this.renderedHTML_ = element.innerHTML /** * @private * @type {ol.proj.Projection} */ this.mapProjection_ = null /** * @private * @type {?ol.TransformFunction} */ this.transform_ = null /** * @private * @type {ol.Pixel} */ this.lastMouseMovePixel_ = null /** * 是否显示跟随气泡（同步开启点击锚坐标） * @type {boolean} * @private */ this.followMouse_ = options['followMouse'] === true ? options['followMouse'] : false /** * 当前气泡 * @type {null} * @private */ this.popver_ = null /** * 容器边界 * @type {null} * @private */ this._bounds = null } ol.inherits(ol.control.MousePositionH, ol.control.Control) /** * 更新控件元素 * @param mapEvent */ ol.control.MousePositionH.render = function (mapEvent) { let frameState = mapEvent.frameState if (!frameState) { this.mapProjection_ = null } else { if (this.mapProjection_ !== frameState.viewState.projection) { this.mapProjection_ = frameState.viewState.projection this.transform_ = null } } if (this.getMap() &amp;&amp; this.lastMouseMovePixel_) { if (this.followMouse_) { this.followMousePopver_(this.lastMouseMovePixel_) } else { this.updateHTML_(this.lastMouseMovePixel_) } } } /** * 处理投影变化事件 * @private */ ol.control.MousePositionH.prototype.handleProjectionChanged_ = function () { this.transform_ = null } /** * 获取投影转换函数 * @returns {ol.CoordinateFormatType|undefined} */ ol.control.MousePositionH.prototype.getCoordinateFormat = function () { return (this.get(ol.control.MousePositionH.Property_.COORDINATE_FORMAT)) } /** * 获取投影 * @returns {ol.proj.Projection|undefined} */ ol.control.MousePositionH.prototype.getProjection = function () { return (this.get(ol.control.MousePositionH.Property_.PROJECTION)) } /** * 处理鼠标移动事件 * @param event */ ol.control.MousePositionH.prototype.handleMouseMove = function (event) { let map = this.getMap() if (map) { this.lastMouseMovePixel_ = map.getEventPixel(event) if (this.lastMouseMovePixel_) { if (this.followMouse_) { this.followMousePopver_(event) } else { this.updateHTML_(this.lastMouseMovePixel_) } } } } /** * 显示气泡 * @param event * @private */ ol.control.MousePositionH.prototype.followMousePopver_ = function () { let html = this.getHTML_(this.lastMouseMovePixel_) let map = this.getMap() let coordinates = map.getCoordinateFromPixel(this.lastMouseMovePixel_) if (!this.popver_) { let ele = htmlUtils.create('div', this.className_ + '_overlay') ele.innerHTML = html this.popver_ = new ol.Overlay({ element: ele, offset: [10, 0], position: coordinates, positioning: 'center-left' }) map.addOverlay(this.popver_) map.render() } else { let _ele = this.popver_.getElement() _ele.innerHTML = html if (_ele.offsetWidth &gt;= this._bounds.width - this.lastMouseMovePixel_[0]) { this.popver_.setPositioning('center-right') this.popver_.setOffset([-10, 0]) } else { this.popver_.setPositioning('center-left') this.popver_.setOffset([10, 0]) } this.popver_.setPosition(coordinates) this.popver_.setElement(_ele) } } /** * 处理鼠标移出视图事件 * @param event */ ol.control.MousePositionH.prototype.handleMouseOut = function (event) { this.updateHTML_(null) this.lastMouseMovePixel_ = null } /** * setMap * @param map */ ol.control.MousePositionH.prototype.setMap = function (map) { ol.control.Control.prototype.setMap.call(this, map) if (map) { let viewport = map.getViewport() this._bounds = map.getTargetElement().getBoundingClientRect() Events.listen(viewport, 'mousemove', this.handleMouseMove, this) Events.listen(viewport, 'mouseout', this.handleMouseOut, this) } } /** * 设置坐标格式化函数 * @param format */ ol.control.MousePositionH.prototype.setCoordinateFormat = function (format) { this.set(ol.control.MousePositionH.Property_.COORDINATE_FORMAT, format) } /** * 设置投影转换 * @param projection */ ol.control.MousePositionH.prototype.setProjection = function (projection) { this.set(ol.control.MousePositionH.Property_.PROJECTION, ol.proj.get(projection)) } /** * 设置显示单位 * @param units */ ol.control.MousePositionH.prototype.setUnits = function (units) { this.set(ol.control.MousePositionH.Property_.PROJECTION, units) } /** * 更新页面控件 * @param pixel * @private */ ol.control.MousePositionH.prototype.updateHTML_ = function (pixel) { let html = this.getHTML_(pixel) if (!this.renderedHTML_ || html !== this.renderedHTML_) { this.element.innerHTML = html this.renderedHTML_ = html } } /** * 获取dom * @param pixel * @returns {string|*} * @private */ ol.control.MousePositionH.prototype.getHTML_ = function (pixel) { let html = this.undefinedHTML_ if (pixel &amp;&amp; this.mapProjection_) { if (!this.transform_) { let projection = this.getProjection() if (projection) { this.transform_ = ol.proj.getTransformFromProjections( this.mapProjection_, projection) } else { this.transform_ = ol.control.MousePositionH.identityTransform } } let map = this.getMap() let coordinate = map.getCoordinateFromPixel(pixel) if (coordinate) { this.transform_(coordinate, coordinate) let coordinateFormat = this.getCoordinateFormat() if (coordinateFormat) { html = coordinateFormat(coordinate) } else { html = ol.control.MousePositionH.Property_.UNITS[0] + '：' + coordinate[0] + ' ' + ol.control.MousePositionH.Property_.UNITS[1] + '：' + coordinate[1] } } } return html } /** * 属性 * @type {{PROJECTION: string, COORDINATE_FORMAT: string}} * @private */ ol.control.MousePositionH.Property_ = { PROJECTION: 'projection', COORDINATE_FORMAT: 'coordinateFormat', UNITS: ['经度', '纬度'] } /** * 转换 * @param input * @param output * @param dimension * @returns {*} */ ol.control.MousePositionH.identityTransform = function (input, output, dimension) { if (output !== undefined &amp;&amp; input !== output) { for (let i = 0, ii = input.length; i &lt; ii; ++i) { output[i] = input[i] } input = output } return input } const olControlMousePosition = ol.control.MousePositionH export default olControlMousePosition × Search results Close "},"control_OverviewMap.js.html":{"id":"control_OverviewMap.js.html","title":"Source: control/OverviewMap.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/OverviewMap.js /** * Created by FDD on 2017/10/12. * @desc 自定义鹰眼控件 */ import { ol } from '../constants' import '../asset/scss/overviewMap.scss' import {BASE_CLASS_NAME, OVERVIEWMAP} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' ol.control.OverviewMapH = function (options = {}) { /** * @type {boolean} * @private */ this.collapsed_ = options.collapsed !== undefined ? options.collapsed : true /** * @private * @type {boolean} */ this.collapsible_ = options.collapsible !== undefined ? options.collapsible : true if (!this.collapsible_) { this.collapsed_ = false } let className = options.className !== undefined ? options.className : 'gmap-overview-map' let element = htmlUtils.create('div', className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE) /** * @type {Element} * @private */ this.ovmapDiv_ = htmlUtils.create('div', 'gmap-overview-map-target', element) /** * 收起按钮 * @type {Element} * @private */ if (this.collapsible_) { this.collapsElement_ = htmlUtils.create('div', 'gmap-overview-map-button', element) Events.listen(this.collapsElement_, 'click', this.handleClick_, this) } /** * @type {ol.Map} * @private */ this.ovmap_ = new ol.Map({ controls: new ol.Collection(), interactions: new ol.Collection(), view: options.view }) let render = options.render ? options.render : ol.control.OverviewMapH.render ol.control.Control.call(this, { element: element, render: render, target: options.target }) this.addBoxControl_() } ol.inherits(ol.control.OverviewMapH, ol.control.Control) /** * 添加图层 * @param options * @private */ ol.control.OverviewMapH.prototype.addOptionLayers_ = function (options) { let ovmap = this.ovmap_ if (options.layers) { options.layers.forEach(function (layer) { ovmap.addLayer(layer) }, this) } } /** * 计算鼠标位置 * @param mousePosition * @returns {{clientX: number, clientY: *}} */ ol.control.OverviewMapH.computeDesiredMousePosition = function (mousePosition, overlayBox) { return { clientX: mousePosition.clientX - (overlayBox.offsetWidth / 2), clientY: mousePosition.clientY + (overlayBox.offsetHeight / 2) } } /** * 处理移动事件 * @private */ ol.control.OverviewMapH.prototype.move_ = function (event) { const overlayBox = this.boxOverlay_.getElement() let coordinates = this.ovmap_.getEventCoordinate(ol.control.OverviewMapH.computeDesiredMousePosition(event, overlayBox)) this.boxOverlay_.setPosition(coordinates) } /** * 移动结束事件 * @param event * @private */ ol.control.OverviewMapH.prototype.endMoving_ = function (event) { let coordinates = this.ovmap_.getEventCoordinate(event) this.getMap().getView().setCenter(coordinates) Events.unListen(window, 'mousemove', this.move_, this) Events.unListen(window, 'mouseup', this.endMoving_, this) } /** * 添加事件 * @private */ ol.control.OverviewMapH.prototype.addEvent_ = function () { Events.listen(window, 'mousemove', this.move_, this) Events.listen(window, 'mouseup', this.endMoving_, this) } /** * 添加box * @private */ ol.control.OverviewMapH.prototype.addBoxControl_ = function () { let box = htmlUtils.create('div', 'gmap-overview-map-box') Events.listen(box, 'mousedown', this.addEvent_, this) this.boxOverlay_ = new ol.Overlay({ position: [0, 0], positioning: 'bottom-left', element: box }) this.ovmap_.addOverlay(this.boxOverlay_) } /** * setMap * @param map */ ol.control.OverviewMapH.prototype.setMap = function (map) { let oldMap = this.getMap() if (map === oldMap) { return } if (oldMap) { let oldView = oldMap.getView() if (oldView) { this.unbindView_(oldView) } this.ovmap_.setTarget(null) } ol.control.Control.prototype.setMap.call(this, map) if (map) { this.ovmap_.setTarget(this.ovmapDiv_) Events.listen(map, 'propertychange', this.handleMapPropertyChange_, this) if (this.ovmap_.getLayers().getLength() === 0) { this.ovmap_.setLayerGroup(map.getLayerGroup()) } let view = map.getView() if (view) { this.bindView_(view) if (this.isDef(view)) { this.ovmap_.updateSize() this.resetExtent_() } } } } /** * 判断视图是否定义 * @param view * @returns {boolean} */ ol.control.OverviewMapH.prototype.isDef = function (view) { return !!view.getCenter() &amp;&amp; view.getResolution() !== undefined } /** * 处理地图属性变化 * @param event * @private */ ol.control.OverviewMapH.prototype.handleMapPropertyChange_ = function (event) { if (event.key === 'view') { let oldView = (event.oldValue) if (oldView) { this.unbindView_(oldView) } let newView = this.getMap().getView() this.bindView_(newView) } } /** * 注册视图变化事件 * @param view * @private */ ol.control.OverviewMapH.prototype.bindView_ = function (view) { Events.listen(view, 'change:rotation', this.handleRotationChanged_, this) } /** * 取消视图事件绑定 * @param view * @private */ ol.control.OverviewMapH.prototype.unbindView_ = function (view) { Events.unListen(view, 'change:rotation', this.handleRotationChanged_, this) } /** * 处理视图旋转 * @private */ ol.control.OverviewMapH.prototype.handleRotationChanged_ = function () { this.ovmap_.getView().setRotation(this.getMap().getView().getRotation()) } /** * 更新控件要素 * @param mapEvent */ ol.control.OverviewMapH.render = function (mapEvent) { this.validateExtent_() this.updateBox_() } /** * 重新调整范围，避免过大或者过小 * @private */ ol.control.OverviewMapH.prototype.validateExtent_ = function () { let map = this.getMap() let ovmap = this.ovmap_ let mapSize = /** @type {ol.Size} */ (map.getSize()) let view = map.getView() let extent = view.calculateExtent(mapSize) let ovmapSize = /** @type {ol.Size} */ (ovmap.getSize()) let ovview = ovmap.getView() let ovextent = ovview.calculateExtent(ovmapSize) let topLeftPixel = ovmap.getPixelFromCoordinate(ol.extent.getTopLeft(extent)) let bottomRightPixel = ovmap.getPixelFromCoordinate(ol.extent.getBottomRight(extent)) let boxWidth = Math.abs(topLeftPixel[0] - bottomRightPixel[0]) let boxHeight = Math.abs(topLeftPixel[1] - bottomRightPixel[1]) let ovmapWidth = ovmapSize[0] let ovmapHeight = ovmapSize[1] if (boxWidth &lt; ovmapWidth * OVERVIEWMAP.MIN_RATIO || boxHeight &lt; ovmapHeight * OVERVIEWMAP.MIN_RATIO || boxWidth &gt; ovmapWidth * OVERVIEWMAP.MAX_RATIO || boxHeight &gt; ovmapHeight * OVERVIEWMAP.MAX_RATIO) { this.resetExtent_() } else if (!ol.extent.containsExtent(ovextent, extent)) { this.recenter_() } } /** * 重新设置视图范围 * @private */ ol.control.OverviewMapH.prototype.resetExtent_ = function () { if (OVERVIEWMAP.MAX_RATIO === 0 || OVERVIEWMAP.MIN_RATIO === 0) { return } let map = this.getMap() let ovmap = this.ovmap_ let mapSize = /** @type {ol.Size} */ (map.getSize()) let view = map.getView() let extent = view.calculateExtent(mapSize) let ovview = ovmap.getView() let steps = Math.log( OVERVIEWMAP.MAX_RATIO / OVERVIEWMAP.MIN_RATIO) / Math.LN2 let ratio = 1 / (Math.pow(2, steps / 2) * OVERVIEWMAP.MIN_RATIO) this.scaleFromCenter(extent, ratio) ovview.fit(extent) } /** * 计算缩放 * @param extent * @param value */ ol.control.OverviewMapH.prototype.scaleFromCenter = function (extent, value) { let deltaX = ((extent[2] - extent[0]) / 2) * (value - 1) let deltaY = ((extent[3] - extent[1]) / 2) * (value - 1) extent[0] -= deltaX extent[2] += deltaX extent[1] -= deltaY extent[3] += deltaY } /** * 重新设置视图中心 * @private */ ol.control.OverviewMapH.prototype.recenter_ = function () { let map = this.getMap() let ovmap = this.ovmap_ let view = map.getView() let ovview = ovmap.getView() ovview.setCenter(view.getCenter()) } /** * Update the box using the main map extent * @private */ ol.control.OverviewMapH.prototype.updateBox_ = function () { let map = this.getMap() let ovmap = this.ovmap_ let mapSize = /** @type {ol.Size} */ (map.getSize()) let view = map.getView() let ovview = ovmap.getView() let rotation = view.getRotation() let overlay = this.boxOverlay_ let box = this.boxOverlay_.getElement() let extent = view.calculateExtent(mapSize) let ovresolution = ovview.getResolution() let bottomLeft = ol.extent.getBottomLeft(extent) let topRight = ol.extent.getTopRight(extent) let rotateBottomLeft = this.calculateCoordinateRotate_(rotation, bottomLeft) overlay.setPosition(rotateBottomLeft) if (box) { box.style.width = Math.abs((bottomLeft[0] - topRight[0]) / ovresolution) + 'px' box.style.height = Math.abs((topRight[1] - bottomLeft[1]) / ovresolution) + 'px' } } /** * 计算坐标角度 * @param rotation * @param coordinate * @returns {*} * @private */ ol.control.OverviewMapH.prototype.calculateCoordinateRotate_ = function (rotation, coordinate) { let coordinateRotate let map = this.getMap() let view = map.getView() let currentCenter = view.getCenter() if (currentCenter) { coordinateRotate = [ coordinate[0] - currentCenter[0], coordinate[1] - currentCenter[1] ] ol.coordinate.rotate(coordinateRotate, rotation) ol.coordinate.add(coordinateRotate, currentCenter) } return coordinateRotate } /** * 处理点击事件 * @param event * @private */ ol.control.OverviewMapH.prototype.handleClick_ = function (event) { event.preventDefault() this.handleToggle_() } /** * @private */ ol.control.OverviewMapH.prototype.handleToggle_ = function () { if (this.collapsed_) { this.collapsed_ = false event.target.style.backgroundPosition = '-40px -405px' this.element.style.width = '17px' this.element.style.height = '17px' } else { this.collapsed_ = true event.target.style.backgroundPosition = '-40px -386px' this.element.style.width = '120px' this.element.style.height = '120px' } let ovmap = this.ovmap_ if (!this.collapsed_ &amp;&amp; !ovmap) { ovmap.updateSize() this.resetExtent_() Events.listenOnce(ovmap, 'postrender', this.updateBox_, this) } } /** * 返回鹰眼是否可折叠 * @returns {*|boolean} */ ol.control.OverviewMapH.prototype.getCollapsible = function () { return this.collapsible_ } /** * 设置鹰眼是否可折叠 * @param collapsible */ ol.control.OverviewMapH.prototype.setCollapsible = function (collapsible) { if (this.collapsible_ === collapsible) { return } this.collapsible_ = collapsible if (!collapsible &amp;&amp; this.collapsed_) { this.handleToggle_() } } /** * 设置鹰眼收起状态 * @param collapsed */ ol.control.OverviewMapH.prototype.setCollapsed = function (collapsed) { if (!this.collapsible_ || this.collapsed_ === collapsed) { return } this.handleToggle_() } /** * 判断鹰眼是否收起 * @returns {boolean|*} */ ol.control.OverviewMapH.prototype.getCollapsed = function () { return this.collapsed_ } /** * 返回当前鹰眼 * @returns {ol.Map} */ ol.control.OverviewMapH.prototype.getOverviewMap = function () { return this.ovmap_ } const olControlOverviewMap = ol.control.OverviewMapH export default olControlOverviewMap × Search results Close "},"control_RotateControl.js.html":{"id":"control_RotateControl.js.html","title":"Source: control/RotateControl.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/RotateControl.js /** * Created by FDD on 2017/9/20. * @desc 视图旋转控制器 */ import { ol } from '../constants' import '../asset/scss/rotate.scss' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' ol.control.RotateControl = function (params = {}) { this.className = params.className !== undefined ? params.className : 'gmap-rotate-control' let render = params.render ? params.render : ol.control.RotateControl.render /** * 重置回调 */ this.callResetNorth_ = params.resetNorth ? params.resetNorth : undefined /** * 动画时延 * @type {number} * @private */ this.duration_ = params.duration !== undefined ? params.duration : 250 /** * 是否自动隐藏 */ this.autoHide_ = params.autoHide !== undefined ? params.autoHide : true /** * element */ let element = this.initDomInternal_(this.className) /** * 旋转角度 * @type {undefined} * @private */ this.rotation_ = undefined ol.control.Control.call(this, { element: element, render: render, target: params.target }) } ol.inherits(ol.control.RotateControl, ol.control.Control) /** * 初始化dom * @private */ ol.control.RotateControl.prototype.initDomInternal_ = function (className) { let element = htmlUtils.create('div', (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) let rButton = htmlUtils.create('button', className + '-inner right-button', element) let cButton = htmlUtils.create('button', className + '-inner center-button', element, className + '-inner-center') this.label_ = cButton let lButton = htmlUtils.create('button', className + '-inner left-button', element) Events.listen(rButton, 'click', ol.control.RotateControl.prototype.handleClick_.bind(this, 'right')) Events.listen(cButton, 'click', ol.control.RotateControl.prototype.handleClick_.bind(this, 'center')) Events.listen(lButton, 'click', ol.control.RotateControl.prototype.handleClick_.bind(this, 'left')) return element } /** * 处理点击事件 * @param type * @param event * @private */ ol.control.RotateControl.prototype.handleClick_ = function (type, event) { event.preventDefault() this.resetNorth_(type) } /** * 恢复正北方向 * @private */ ol.control.RotateControl.prototype.resetNorth_ = function (type) { let rotation = 0 if (type === 'center') { rotation = 0 if (this.callResetNorth_ !== undefined) { this.callResetNorth_() } else { this.rotationView_(rotation, type) } } else if (type === 'left') { rotation = -90 this.rotationView_(rotation) } else { rotation = 90 this.rotationView_(rotation) } } /** * 旋转视图 * @param rotation * @param type * @private */ ol.control.RotateControl.prototype.rotationView_ = function (rotation, type) { let map = this.getMap() let view = map.getView() let r = type === 'center' ? 0 : view.getRotation() + (rotation / 180 * Math.PI) if (view &amp;&amp; view instanceof ol.View) { if (view.getRotation() !== undefined) { if (this.duration_ &gt; 0) { view.animate({ rotation: r, duration: this.duration_, easing: ol.easing.easeOut }) } else { view.setRotation(0) } } } else { throw new Error('未获取到视图！') } } /** * 根据视图更新dom * @param mapEvent */ ol.control.RotateControl.render = function (mapEvent) { let frameState = mapEvent.frameState if (!frameState) { return } let rotation = frameState.viewState.rotation if (rotation !== this.rotation_) { let transform = 'rotate(' + rotation + 'rad)' if (this.autoHide_) { let contains = this.element.classList.contains(BASE_CLASS_NAME.CLASS_HIDDEN) if (!contains &amp;&amp; rotation === 0) { this.element.classList.add(BASE_CLASS_NAME.CLASS_HIDDEN) } else if (contains &amp;&amp; rotation !== 0) { this.element.classList.remove(BASE_CLASS_NAME.CLASS_HIDDEN) } } this.label_.style.msTransform = transform this.label_.style.webkitTransform = transform this.label_.style.transform = transform } this.rotation_ = rotation } let olControlRotate = ol.control.RotateControl export default olControlRotate × Search results Close "},"control_ScaleLineH.js.html":{"id":"control_ScaleLineH.js.html","title":"Source: control/ScaleLineH.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/ScaleLineH.js /** * Created by FDD on 2017/10/11. * @desc 比例尺控件 */ import { ol } from '../constants' import '../asset/scss/ScaleLineH.scss' import {BASE_CLASS_NAME, UNITS} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' ol.control.ScaleLineH = function (options = {}) { const className = options.className !== undefined ? options.className : 'gmap-scale-line-control' /** * @private * @type {Element} */ this.element_ = htmlUtils.create('div', (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) /** * @private * @type {Element} */ this.innerElement_ = htmlUtils.create('div', (className + '-inner'), this.element_) /** * @private * @type {?olx.ViewState} */ this.viewState_ = null /** * @private * @type {number} */ this.minWidth_ = options.minWidth !== undefined ? options.minWidth : 64 /** * @private * @type {boolean} */ this.renderedVisible_ = false /** * @private * @type {number|undefined} */ this.renderedWidth_ = undefined /** * @private * @type {string} */ this.renderedHTML_ = '' const render = options.render ? options.render : ol.control.ScaleLineH.render ol.control.Control.call(this, { element: this.element_, render: render, target: options.target }) Events.listen(this, 'change:' + ol.control.ScaleLineH.Property_.UNITS, this.handleUnitsChanged_, this) this.setUnits((options.units) || ol.control.ScaleLineH.ScaleLineUnits.METRIC) } ol.inherits(ol.control.ScaleLineH, ol.control.Control) /** * @const * @type {Array.&lt;number&gt;} */ ol.control.ScaleLineH.LEADING_DIGITS = [1, 2, 5] /** * 内置单位 * @type {{DEGREES: string, IMPERIAL: string, NAUTICAL: string, METRIC: string, CHINESEMETRIC: string, US: string}} */ ol.control.ScaleLineH.ScaleLineUnits = { DEGREES: 'degrees', IMPERIAL: 'imperial', NAUTICAL: 'nautical', METRIC: 'metric', CHINESEMETRIC: 'metric_cn', US: 'us' } /** * 返回比例尺使用的单位 * @returns {*} */ ol.control.ScaleLineH.prototype.getUnits = function () { return (this.get(ol.control.ScaleLineH.Property_.UNITS)) } /** * 更新element * @param mapEvent */ ol.control.ScaleLineH.render = function (mapEvent) { let frameState = mapEvent.frameState if (!frameState) { this.viewState_ = null } else { this.viewState_ = frameState.viewState } this.updateElement_() } /** * 处理单位变化事件 * @private */ ol.control.ScaleLineH.prototype.handleUnitsChanged_ = function () { this.updateElement_() } /** * 设置使用的单位 * @param units */ ol.control.ScaleLineH.prototype.setUnits = function (units) { this.set(ol.control.ScaleLineH.Property_.UNITS, units) } /** * 更新element * @private */ ol.control.ScaleLineH.prototype.updateElement_ = function () { let viewState = this.viewState_ if (!viewState) { if (this.renderedVisible_) { this.element_.style.display = 'none' this.renderedVisible_ = false } return } let [center, projection] = [viewState.center, viewState.projection] let units = this.getUnits() let pointResolutionUnits = units === ol.control.ScaleLineH.ScaleLineUnits.DEGREES ? UNITS.DEGREES : UNITS.METERS let pointResolution = ol.proj.getPointResolution(projection, viewState.resolution, center, pointResolutionUnits) let nominalCount = this.minWidth_ * pointResolution let suffix = '' if (units === ol.control.ScaleLineH.ScaleLineUnits.DEGREES) { let metersPerDegree = ol.proj.METERS_PER_UNIT[UNITS.DEGREES] if (projection.getUnits() === UNITS.DEGREES) { nominalCount *= metersPerDegree } else { pointResolution /= metersPerDegree } if (nominalCount &lt; metersPerDegree / 60) { suffix = '\\u2033' // seconds pointResolution *= 3600 } else if (nominalCount &lt; metersPerDegree) { suffix = '\\u2032' // minutes pointResolution *= 60 } else { suffix = '\\u00b0' // degrees } } else if (units === ol.control.ScaleLineH.ScaleLineUnits.IMPERIAL) { if (nominalCount &lt; 0.9144) { suffix = 'in' pointResolution /= 0.0254 } else if (nominalCount &lt; 1609.344) { suffix = 'ft' pointResolution /= 0.3048 } else { suffix = 'mi' pointResolution /= 1609.344 } } else if (units === ol.control.ScaleLineH.ScaleLineUnits.NAUTICAL) { pointResolution /= 1852 suffix = 'nm' } else if (units === ol.control.ScaleLineH.ScaleLineUnits.METRIC) { if (nominalCount &lt; 0.001) { suffix = 'μm' pointResolution *= 1000000 } else if (nominalCount &lt; 1) { suffix = 'mm' pointResolution *= 1000 } else if (nominalCount &lt; 1000) { suffix = 'm' } else { suffix = 'km' pointResolution /= 1000 } } else if (units === ol.control.ScaleLineH.ScaleLineUnits.US) { if (nominalCount &lt; 0.9144) { suffix = 'in' pointResolution *= 39.37 } else if (nominalCount &lt; 1609.344) { suffix = 'ft' pointResolution /= 0.30480061 } else { suffix = 'mi' pointResolution /= 1609.3472 } } else if (units === ol.control.ScaleLineH.ScaleLineUnits.CHINESEMETRIC) { if (nominalCount &lt; 0.001) { suffix = '微米' pointResolution *= 1000000 } else if (nominalCount &lt; 1) { suffix = '毫米' pointResolution *= 1000 } else if (nominalCount &lt; 1000) { suffix = '米' } else { suffix = '千米' pointResolution /= 1000 } } else { ol.asserts.assert(false, 33) // Invalid units } let i = 3 * Math.floor( Math.log(this.minWidth_ * pointResolution) / Math.log(10)) let [count, width] = [] while (true) { count = ol.control.ScaleLineH.LEADING_DIGITS[((i % 3) + 3) % 3] * Math.pow(10, Math.floor(i / 3)) width = Math.round(count / pointResolution) if (isNaN(width)) { this.element_.style.display = 'none' this.renderedVisible_ = false return } else if (width &gt;= this.minWidth_) { break } ++i } let html = count + ' ' + suffix if (this.renderedHTML_ !== html) { this.innerElement_.innerHTML = html this.renderedHTML_ = html } if (this.renderedWidth_ !== width) { this.innerElement_.style.width = width + 'px' this.renderedWidth_ = width } if (!this.renderedVisible_) { this.element_.style.display = '' this.renderedVisible_ = true } } /** * @enum {string} * @private */ ol.control.ScaleLineH.Property_ = { UNITS: 'units' } const olControlScaleLine = ol.control.ScaleLineH export default olControlScaleLine × Search results Close "},"control_zoom.js.html":{"id":"control_zoom.js.html","title":"Source: control/zoom.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: control/zoom.js /** * @desc 缩放按钮 */ import { ol } from '../constants' import '../asset/scss/zoom.scss' import {BASE_CLASS_NAME} from '../constants' import * as htmlUtils from '../utils/domUtils' import * as Events from '../event/Events' import {EventType} from '../event/EventType' ol.control.ZoomMenu = function (params = {}) { this.options = params /** * 基础类名 * @type {string} */ let className = this.options.className !== undefined ? this.options.className : 'gmap-control-zoom' /** * delta */ let delta = this.options.delta !== undefined ? this.options.delta : 1 let element_ = this.initDomInternal_(className, delta) /** * 动画时间 * @type {number} * @private */ this.duration_ = this.options.duration !== undefined ? this.options.duration : 250 ol.control.Control.call(this, { element: element_, target: this.options.target }) } ol.inherits(ol.control.ZoomMenu, ol.control.Control) /** * 初始化相关dom * @param className * @param delta * @returns {Element} * @private */ ol.control.ZoomMenu.prototype.initDomInternal_ = function (className, delta) { let element = htmlUtils.create('div', (className + ' ' + BASE_CLASS_NAME.CLASS_UNSELECTABLE)) let zoomin = htmlUtils.create('span', 'zoom-in', element) zoomin.setAttribute('title', '放大') zoomin.innerHTML = '+' let zoomout = htmlUtils.create('span', 'zoom-out', element) zoomout.setAttribute('title', '缩小') zoomout.innerHTML = '\\u2212' Events.listen(zoomin, EventType.CLICK, ol.control.ZoomMenu.prototype.handleClick_.bind(this, delta)) Events.listen(zoomout, EventType.CLICK, ol.control.ZoomMenu.prototype.handleClick_.bind(this, -delta)) return element } /** * 处理点击事件 * @param delta * @param event * @private */ ol.control.ZoomMenu.prototype.handleClick_ = function (delta, event) { event.preventDefault() this.zoomByDelta_(delta) } /** * 缩放控制 * @param delta * @private */ ol.control.ZoomMenu.prototype.zoomByDelta_ = function (delta) { let map = this.getMap() let view = map.getView() if (!view) { throw new Error('未获取到视图！') } else { let currentResolution = view.getResolution() if (currentResolution) { let newResolution = view.constrainResolution(currentResolution, delta) if (this.duration_ &gt; 0) { if (view.getAnimating()) { view.cancelAnimations() } view.animate({ resolution: newResolution, duration: this.duration_, easing: ol.easing.easeOut }) } else { view.setResolution(newResolution) } } } } let olControlZoomMenu = ol.control.ZoomMenu export default olControlZoomMenu × Search results Close "},"utils_layerUtils.js.html":{"id":"utils_layerUtils.js.html","title":"Source: utils/layerUtils.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: utils/layerUtils.js import { ol } from '../constants' ol.layer.LayerUtils = function (map) { if (map &amp;&amp; map instanceof ol.Map) { this.map = map } else { throw new Error('传入的不是地图对象！') } } /** * 通过layerName获取图层 * @param layerName * @returns {*} */ ol.layer.LayerUtils.prototype.getLayerByLayerName = function (layerName) { try { let targetLayer = null if (this.map) { let layers = this.map.getLayers().getArray() targetLayer = this.getLayerInternal(layers, 'layerName', layerName) } return targetLayer } catch (e) { console.log(e) } } /** * 内部处理获取图层方法 * @param layers * @param key * @param value * @returns {*} */ ol.layer.LayerUtils.prototype.getLayerInternal = function (layers, key, value) { let _target = null if (layers.length &gt; 0) { layers.every(layer =&gt; { if (layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() _target = this.getLayerInternal(layers, key, value) if (_target) { return false } else { return true } } else if (layer.get(key) === value) { _target = layer return false } else { return true } }) } return _target } /** * 根据相关键值键名获取图层集合 * @param layers * @param key * @param value * @returns {Array} */ ol.layer.LayerUtils.prototype.getLayersArrayInternal = function (layers, key, value) { let _target = [] if (layers.length &gt; 0) { layers.forEach(layer =&gt; { if (layer instanceof ol.layer.Group) { let layers = layer.getLayers().getArray() let _layer = this.getLayersArrayInternal(layers, key, value) if (_layer) { _target = _target.concat(_layer) } } else if (layer.get(key) === value) { _target.push(layer) } }) } return _target } /** * 通过键名键值获取图层（注意键名键值必须是set(key, value)） * @param key * @param value */ ol.layer.LayerUtils.prototype.getLayerByKeyValue = function (key, value) { try { let targetLayer = null if (this.map) { let layers = this.map.getLayers().getArray() targetLayer = this.getLayerInternal(layers, key, value) } return targetLayer } catch (e) { console.log(e) } } /** * 通过键名键值获取图层集合（注意键名键值必须是set(key, value)） * @param key * @param value */ ol.layer.LayerUtils.prototype.getLayersArrayByKeyValue = function (key, value) { try { let targetLayers = [] if (this.map) { let layers = this.map.getLayers().getArray() targetLayers = this.getLayersArrayInternal(layers, key, value) } return targetLayers } catch (e) { console.log(e) } } /** * 创建临时图层 * @param layerName * @param params * @returns {*} */ ol.layer.LayerUtils.prototype.createVectorLayer = function (layerName, params) { try { if (this.map) { let vectorLayer = this.getLayerByLayerName(layerName) if (!(vectorLayer instanceof ol.layer.Vector)) { vectorLayer = null } if (!vectorLayer) { if (params &amp;&amp; params.create) { vectorLayer = new ol.layer.Vector({ layerName: layerName, params: params, layerType: 'vector', source: new ol.source.Vector({ wrapX: false }), style: new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(67, 110, 238, 0.4)' }), stroke: new ol.style.Stroke({ color: '#4781d9', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }) }) } } if (this.map &amp;&amp; vectorLayer) { if (params &amp;&amp; params.hasOwnProperty('selectable')) { vectorLayer.set('selectable', params.selectable) } // 图层只添加一次 let _vectorLayer = this.getLayerByLayerName(layerName) if (!_vectorLayer || !(_vectorLayer instanceof ol.layer.Vector)) { this.map.addLayer(vectorLayer) } } return vectorLayer } } catch (e) { console.log(e) } } let olLayerLayerUtils = ol.layer.LayerUtils export default olLayerLayerUtils × Search results Close "},"overlay_popupoverlay.js.html":{"id":"overlay_popupoverlay.js.html","title":"Source: overlay/popupoverlay.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: overlay/popupoverlay.js /* Copyright (c) 2016 Jean-Marc VIGLINO, released under the CeCILL-B license (French BSD license) (http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.txt). */ /** * @classdesc * A popup element to be displayed over the map and attached to a single map * location. Like {@link ol.control.Control}, Overlays are visible widgets. * Unlike Controls, they are not in a fixed position on the screen, but are tied * to a geographical coordinate, so panning the map will move an Overlay but not * a Control. * * Example: * * var popup = new ol.Overlay.Popup(); * map.addOverlay(popup); * popup.show(coordinate, &quot;Hello!&quot;); * popup.hide(); * * @constructor * @extends {ol.Overlay} * @param {olx.OverlayOptions} options Overlay options * + popupClass: the a class for the overlay. * + closeBox: popup has a close box. * + onclose: callback when popup is closed * + onshow: callback when popup is shown * + positionning: add 'auto' to let the popup choose a good positioning. * @api stable */ ol.Overlay.Popup = function (options) { var self = this; var elt = $(&quot;&lt;div&gt;&quot;); this.element = options.element = elt.get(0); this.offsetBox = options.offsetBox; // Anchor div $(&quot;&lt;div&gt;&quot;).addClass(&quot;anchor&quot;).appendTo(elt); var d = $(&quot;&lt;div&gt;&quot;).addClass('ol-overlaycontainer-stopevent').appendTo(elt); // header var header=$(&quot;&lt;div&gt;&quot;).addClass(&quot;header&quot;).prependTo(d); var title=$(&quot;&lt;span&gt;&quot;).addClass(&quot;title&quot;).appendTo(header); // content this.content = $(&quot;&lt;div&gt;&quot;).addClass(&quot;content&quot;).appendTo(d).get(0); //设置标题 this.title = options.title; // Closebox this.closeBox = options.closeBox; this.onclose = options.onclose; this.onshow = options.onshow; $(&quot;&lt;button&gt;&quot;).addClass(&quot;closeBox&quot;).addClass(options.closeBox?&quot;hasclosebox&quot;:&quot;&quot;) .attr('type', 'button') .appendTo(header) .click(function() { self.hide(); }); // Stop event options.stopEvent=true; d.on(&quot;mousedown touchstart&quot;, function(event){ event.stopPropagation(); }) ol.Overlay.call(this, options); // call setPositioning first in constructor so getClassPositioning is called only once this.setPositioning(options.positioning); this.setPopupClass(options.popupClass); this.setTitle(options.title) } ol.inherits(ol.Overlay.Popup, ol.Overlay); /** * Get CSS class of the popup according to its positioning. * @private */ ol.Overlay.Popup.prototype.getClassPositioning = function () { var c = &quot;&quot;; var pos = this.getPositioning(); if (/bottom/.test(pos)) c += &quot;ol-popup-bottom &quot;; if (/top/.test(pos)) c += &quot;ol-popup-top &quot;; if (/left/.test(pos)) c += &quot;ol-popup-left &quot;; if (/right/.test(pos)) c += &quot;ol-popup-right &quot;; if (/^center/.test(pos)) c += &quot;ol-popup-middle &quot;; if (/center$/.test(pos)) c += &quot;ol-popup-center &quot;; return c; } /** * Set CSS class of the popup. * @param {string} class name. * @api stable */ ol.Overlay.Popup.prototype.setClosebox = function (b) { this.closeBox = b; if (b) $(this.element).addClass(&quot;hasclosebox&quot;); else $(this.element).removeClass(&quot;hasclosebox&quot;); } /** * 设置标题 */ ol.Overlay.Popup.prototype.setTitle = function (b) { if (b){ $(this.element).addClass(&quot;hasSetTitle&quot;); $(this.element).find('.title').text(b); } else { $(this.element).removeClass(&quot;hasSetTitle&quot;) } } /** * Set the CSS class of the popup. * @param {string} class name. * @api stable */ ol.Overlay.Popup.prototype.setPopupClass = function (c) { $(this.element).removeClass() .addClass(&quot;ol-popup &quot;+(c||&quot;default&quot;)+&quot; &quot;+this.getClassPositioning()+(this.closeBox?&quot; hasclosebox&quot;:&quot;&quot;)); } /** * Add a CSS class to the popup. * @param {string} class name. * @api stable */ ol.Overlay.Popup.prototype.addPopupClass = function (c) { $(this.element).addClass(c); } /** * Remove a CSS class to the popup. * @param {string} class name. * @api stable */ ol.Overlay.Popup.prototype.removePopupClass = function (c) { $(this.element).removeClass(c); } /** * Remove a CSS class to the popup. * @param {string} class name. * @api stable */ ol.Overlay.Popup.prototype.setPositioning = function (pos) { if (pos === undefined) return; if (/auto/.test(pos)) { this.autoPositioning = pos.split('-'); if (this.autoPositioning.length==1) this.autoPositioning[1]=&quot;auto&quot;; } else this.autoPositioning = false; pos = pos.replace(/auto/g,&quot;center&quot;); if (pos==&quot;center&quot;) pos = &quot;bottom-center&quot;; this.setPositioning_(pos); } ol.Overlay.Popup.prototype.setPositioning_ = function (pos) { ol.Overlay.prototype.setPositioning.call(this, pos); $(this.element).removeClass(&quot;ol-popup-top ol-popup-bottom ol-popup-left ol-popup-right ol-popup-center ol-popup-middle&quot;); $(this.element).addClass(this.getClassPositioning()); } /** Check if popup is visible * @return {boolean} */ ol.Overlay.Popup.prototype.getVisible = function () { return $(this.element).hasClass(&quot;visible&quot;); }; /** * Set the position and the content of the popup. * @param {ol.Coordinate|string} the coordinate of the popup or the HTML content. * @param {string|undefined} the HTML content (undefined = previous content). * @api stable */ ol.Overlay.Popup.prototype.show = function (coordinate, html) { if (!html &amp;&amp; typeof(coordinate)=='string') { html = coordinate; coordinate = null; } var self = this; var map = this.getMap(); if (!map) return; if (html &amp;&amp; html !== this.prevHTML) { // Prevent flickering effect this.prevHTML = html; $(this.content).html(&quot;&quot;).append(html); // Refresh when loaded (img) $(&quot;*&quot;, this.content).on('load',function() { map.renderSync(); }) } if (coordinate) { // Auto positionning if (this.autoPositioning) { var p = map.getPixelFromCoordinate(coordinate); var s = map.getSize(); var pos=[]; if (this.autoPositioning[0]=='auto') { pos[0] = (p[1]&lt;s[1]/3) ? &quot;top&quot; : &quot;bottom&quot;; } else pos[0] = this.autoPositioning[0]; pos[1] = (p[0]&lt;2*s[0]/3) ? &quot;left&quot; : &quot;right&quot;; this.setPositioning_(pos[0]+&quot;-&quot;+pos[1]); if (this.offsetBox) { this.setOffset([this.offsetBox[pos[1]==&quot;left&quot;?2:0], this.offsetBox[pos[0]==&quot;top&quot;?3:1] ]); } } // Show this.setPosition(coordinate); // Set visible class (wait to compute the size/position first) $(this.element).parent().show(); if (typeof (this.onshow) == 'function') this.onshow(); this._tout = setTimeout (function() { $(self.element).addClass(&quot;visible&quot;); }, 0); } } /** * Hide the popup * @api stable */ ol.Overlay.Popup.prototype.hide = function () { if (this.getPosition() == undefined) return; if (typeof (this.onclose) == 'function') this.onclose(); this.setPosition(undefined); if (this._tout) clearTimeout(this._tout); $(this.element).removeClass(&quot;visible&quot;); } × Search results Close "},"pointer_PointerEvent.js.html":{"id":"pointer_PointerEvent.js.html","title":"Source: pointer/PointerEvent.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/PointerEvent.js // Based on https://github.com/Polymer/PointerEvents class PointerEvent { constructor (type, originalEvent, optEventDict) { /** * @const * @type {Event} */ this.originalEvent = originalEvent let eventDict = optEventDict || {} /** * @type {number} */ this.buttons = this.getButtons_(eventDict) /** * @type {number} */ this.pressure = this.getPressure_(eventDict, this.buttons) // MouseEvent related properties /** * @type {boolean} */ this.bubbles = 'bubbles' in eventDict ? eventDict['bubbles'] : false /** * @type {boolean} */ this.cancelable = 'cancelable' in eventDict ? eventDict['cancelable'] : false /** * @type {Object} */ this.view = 'view' in eventDict ? eventDict['view'] : null /** * @type {number} */ this.detail = 'detail' in eventDict ? eventDict['detail'] : null /** * @type {number} */ this.screenX = 'screenX' in eventDict ? eventDict['screenX'] : 0 /** * @type {number} */ this.screenY = 'screenY' in eventDict ? eventDict['screenY'] : 0 /** * @type {number} */ this.clientX = 'clientX' in eventDict ? eventDict['clientX'] : 0 /** * @type {number} */ this.clientY = 'clientY' in eventDict ? eventDict['clientY'] : 0 /** * @type {boolean} */ this.ctrlKey = 'ctrlKey' in eventDict ? eventDict['ctrlKey'] : false /** * @type {boolean} */ this.altKey = 'altKey' in eventDict ? eventDict['altKey'] : false /** * @type {boolean} */ this.shiftKey = 'shiftKey' in eventDict ? eventDict['shiftKey'] : false /** * @type {boolean} */ this.metaKey = 'metaKey' in eventDict ? eventDict['metaKey'] : false /** * @type {number} */ this.button = 'button' in eventDict ? eventDict['button'] : 0 /** * @type {Node} */ this.relatedTarget = 'relatedTarget' in eventDict ? eventDict['relatedTarget'] : null // PointerEvent related properties /** * @const * @type {number} */ this.pointerId = 'pointerId' in eventDict ? eventDict['pointerId'] : 0 /** * @type {number} */ this.width = 'width' in eventDict ? eventDict['width'] : 0 /** * @type {number} */ this.height = 'height' in eventDict ? eventDict['height'] : 0 /** * @type {number} */ this.tiltX = 'tiltX' in eventDict ? eventDict['tiltX'] : 0 /** * @type {number} */ this.tiltY = 'tiltY' in eventDict ? eventDict['tiltY'] : 0 /** * @type {string} */ this.pointerType = 'pointerType' in eventDict ? eventDict['pointerType'] : '' /** * @type {number} */ this.hwTimestamp = 'hwTimestamp' in eventDict ? eventDict['hwTimestamp'] : 0 /** * @type {boolean} */ this.isPrimary = 'isPrimary' in eventDict ? eventDict['isPrimary'] : false // keep the semantics of preventDefault if (originalEvent.preventDefault) { this.preventDefault = function () { originalEvent.preventDefault() } } } getButtons_ (eventDict) { let buttons if (eventDict.buttons || PointerEvent.HAS_BUTTONS) { buttons = eventDict.buttons } else { switch (eventDict.which) { case 1: buttons = 1 break case 2: buttons = 4 break case 3: buttons = 2 break default: buttons = 0 } } return buttons } getPressure_ (eventDict, buttons) { // Spec requires that pointers without pressure specified use 0.5 for down // state and 0 for up state. let pressure = 0 if (eventDict.pressure) { pressure = eventDict.pressure } else { pressure = buttons ? 0.5 : 0 } return pressure } preventDefault (evt) { evt.preventDefault() } /** * 是否支持buttons * @type {boolean} */ static HAS_BUTTONS = false } export default PointerEvent × Search results Close "},"pointer_PointerEventHandler.js.html":{"id":"pointer_PointerEventHandler.js.html","title":"Source: pointer/PointerEventHandler.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/PointerEventHandler.js // Based on https://github.com/Polymer/PointerEvents import EventTarget from '../events/EventTarget' import NativeSource from './NativeSource' import MsSource from './MsSource' import MouseSource from './MouseSource' import TouchSource from './TouchSource' import PointerEvent from './PointerEvent' import * as Events from '../events/Events' import {EventType} from '../events/EventType' class PointerEventHandler extends EventTarget { constructor (element) { super() /** * call */ EventTarget.call(this) /** * element */ this.element_ = element /** * @const * @type {!Object.&lt;string, Event|Object&gt;} */ this.pointerMap = {} /** * @type {Object.&lt;string, function(Event)&gt;} * @private */ this.eventMap_ = {} /** * @type {Array.&lt;EventSource&gt;} * @private */ this.eventSourceList_ = [] this.registerSources() } /** * Set up the event sources (mouse, touch and native pointers) * that generate pointer events. */ registerSources () { if ('PointerEvent' in window) { this.registerSource('native', (new NativeSource(this))) } else if (navigator.msPointerEnabled) { this.registerSource('ms', new MsSource(this)) } else { let mouseSource = new MouseSource(this) this.registerSource('mouse', mouseSource) if ('ontouchstart' in window) { this.registerSource('touch', new TouchSource(this, mouseSource)) } } // register events on the viewport element this.register_() } /** * Add a new event source that will generate pointer events. * @param {string} name A name for the event source * @param {EventSource} source The source event. */ registerSource (name, source) { let s = source let newEvents = s.getEvents() if (newEvents) { newEvents.forEach(function (e) { let handler = s.getHandlerForEvent(e) if (handler) { this.eventMap_[e] = handler.bind(s) } }, this) this.eventSourceList_.push(s) } } /** * Set up the events for all registered event sources. * @private */ register_ () { let l = this.eventSourceList_.length let eventSource for (let i = 0; i &lt; l; i++) { eventSource = this.eventSourceList_[i] this.addEvents_(eventSource.getEvents()) } } /** * Remove all registered events. * @private */ unregister_ () { let l = this.eventSourceList_.length let eventSource for (let i = 0; i &lt; l; i++) { eventSource = this.eventSourceList_[i] this.removeEvents_(eventSource.getEvents()) } } /** * Calls the right handler for a new event. * @private * @param {Event} inEvent Browser event. */ eventHandler_ (inEvent) { let type = inEvent.type let handler = this.eventMap_[type] if (handler) { handler(inEvent) } } /** * Setup listeners for the given events. * @private * @param {Array.&lt;string&gt;} events List of events. */ addEvents_ (events) { events.forEach(function (eventName) { Events.listen(this.element_, eventName, this.eventHandler_, this) }, this) } /** * Unregister listeners for the given events. * @private * @param {Array.&lt;string&gt;} events List of events. */ removeEvents_ (events) { events.forEach(function (e) { Events.unListen(this.element_, e, this.eventHandler_, this) }, this) } /** * Returns a snapshot of inEvent, with writable properties. * @param event * @param inEvent * @returns {{}} */ cloneEvent (event, inEvent) { let [eventCopy, p] = [{}, null] for (var i = 0, ii = PointerEventHandler.CLONE_PROPS.length; i &lt; ii; i++) { p = PointerEventHandler.CLONE_PROPS[i][0] eventCopy[p] = event[p] || inEvent[p] || PointerEventHandler.CLONE_PROPS[i][1] } return eventCopy } /** * Triggers a 'pointerdown' event. * @param data * @param event */ down (data, event) { this.fireEvent(EventType.POINTERDOWN, data, event) } /** * Triggers a 'pointermove' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ move (data, event) { this.fireEvent(EventType.POINTERMOVE, data, event) } /** * Triggers a 'pointerup' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ up (data, event) { this.fireEvent(EventType.POINTERUP, data, event) } /** * Triggers a 'pointerenter' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ enter (data, event) { data.bubbles = false this.fireEvent(EventType.POINTERENTER, data, event) } /** * Triggers a 'pointerleave' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ leave (data, event) { data.bubbles = false this.fireEvent(EventType.POINTERLEAVE, data, event) } /** * Triggers a 'pointerover' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ over (data, event) { data.bubbles = true this.fireEvent(EventType.POINTEROVER, data, event) } /** * Triggers a 'pointerout' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ out (data, event) { data.bubbles = true this.fireEvent(EventType.POINTEROUT, data, event) } /** * Triggers a 'pointercancel' event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ cancel (data, event) { this.fireEvent(EventType.POINTERCANCEL, data, event) } /** * Triggers a combination of 'pointerout' and 'pointerleave' events. * @param {Object} data Pointer event data. * @param {Event} event The event. */ leaveOut (data, event) { this.out(data, event) if (!this.contains_(data.target, data.relatedTarget)) { this.leave(data, event) } } /** * Triggers a combination of 'pointerover' and 'pointerevents' events. * @param {Object} data Pointer event data. * @param {Event} event The event. */ enterOver (data, event) { this.over(data, event) if (!this.contains_(data.target, data.relatedTarget)) { this.enter(data, event) } } /** * @private * @param {Element} container The container element. * @param {Element} contained The contained element. * @return {boolean} Returns true if the container element * contains the other element. */ contains_ (container, contained) { if (!container || !contained) { return false } return container.contains(contained) } // EVENT CREATION AND TRACKING /** * Creates a new Event of type `inType`, based on the information in * `data`. * * @param {string} inType A string representing the type of event to create. * @param {Object} data Pointer event data. * @param {Event} event The event. * @return {PointerEvent} A PointerEvent of type `inType`. */ makeEvent (inType, data, event) { return new PointerEvent(inType, event, data) } /** * Make and dispatch an event in one call. * @param {string} inType A string representing the type of event. * @param {Object} data Pointer event data. * @param {Event} event The event. */ fireEvent (inType, data, event) { let e = this.makeEvent(inType, data, event) this.dispatchEvent(e) } /** * Creates a pointer event from a native pointer event * and dispatches this event. * @param {Event} event A platform event with a target. */ fireNativeEvent (event) { let e = this.makeEvent(event.type, event, event) this.dispatchEvent(e) } /** * Wrap a native mouse event into a pointer event. * This proxy method is required for the legacy IE support. * @param {string} eventType The pointer event type. * @param {Event} event The event. * @return {PointerEvent} The wrapped event. */ wrapMouseEvent (eventType, event) { let pointerEvent = this.makeEvent(eventType, MouseSource.prepareEvent(event, this), event) return pointerEvent } /** * @inheritDoc */ disposeInternal () { this.unregister_() EventTarget.prototype.disposeInternal.call(this) } /** * Properties to copy when cloning an event, with default values. * @type {Array.&lt;Array&gt;} */ static CLONE_PROPS = [ // MouseEvent ['bubbles', false], ['cancelable', false], ['view', null], ['detail', null], ['screenX', 0], ['screenY', 0], ['clientX', 0], ['clientY', 0], ['ctrlKey', false], ['altKey', false], ['shiftKey', false], ['metaKey', false], ['button', 0], ['relatedTarget', null], // DOM Level 3 ['buttons', 0], // PointerEvent ['pointerId', 0], ['width', 0], ['height', 0], ['pressure', 0], ['tiltX', 0], ['tiltY', 0], ['pointerType', ''], ['hwTimestamp', 0], ['isPrimary', false], // event instance ['type', ''], ['target', null], ['currentTarget', null], ['which', 0] ] } export default PointerEventHandler × Search results Close "},"style_Style.js.html":{"id":"style_Style.js.html","title":"Source: style/Style.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: style/Style.js import { ol } from '../constants' class Style { /** * 获取点样式 * @param attr * @returns {ol.style.Style} */ getStyleByPoint(attr) { let style = new ol.style.Style({ image: new ol.style.Icon({ anchor: [0.5, 1], anchorXUnits: 'fraction', anchorYUnits: 'fraction', opacity: 0.75, src: '' }) }); return style; } /** * 获取线样式 * @param attr * @returns {ol.style.Style} */ getStyleByLine(attr) { let style = new ol.style.Style({ stroke: new ol.style.Stroke({ width: 4, color: '#0000EE' }) }); return style } /** * 获取面样式 * @param attr * @returns {ol.style.Style} */ getStyleByPolygon(attr) { let style = new ol.style.Style({ text: new ol.style.Text({ font: &quot;30px serif&quot;, fill: new ol.style.Fill({ color: &quot;#E50000&quot; }), text: attr['name'], offsetX: 0.5, offsetY: -15, }), fill: new ol.style.Fill({ color: 'rgba(67, 110, 238, 0.4)' }), stroke: new ol.style.Stroke({ color: '#4781d9', width: 2 }), image: new ol.style.Circle({ radius: 7, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }); return style; } } export default Style × Search results Close "},"map_Tools.js.html":{"id":"map_Tools.js.html","title":"Source: map/Tools.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: map/Tools.js export class Tools { constructor(map, opts) {//opts=[“zoomplus”,“zoomsub”,“initview”] this.map = map; var listener; var output; var sketch; var measureTooltipElement; var measureTooltip; this.init(opts); } init (opts){ var containerDiv = document.createElement('div'); containerDiv.className = 'containerDrawDiv'; // containerDiv.style= &quot; top: 100px;position: absolute;right: 140px;&quot;; containerDiv.style.top=&quot;100px&quot;; containerDiv.style.position=&quot;absolute&quot;; containerDiv.style.right=&quot;140px&quot;; this.map.crtLayer(); for( var i = 0; i&lt;opts.length; i++){ switch(opts[i]) { case &quot;zoomplus&quot;: this.addzoomplusTool(); break; case &quot;zoomsub&quot;: this.addzoomsubTool(); break; case &quot;initview&quot;: this.addinitViewTool(); break; case &quot;drawpointlinepolygon&quot;: containerDiv = this.adddrawPLPTool(containerDiv); this.getAddFeatures(); break; case &quot;linepolygonmeasure&quot;: this.addLineMeasure(); break; case &quot;measureclear&quot;: this.addMeasureClear(containerDiv); break; case &quot;location&quot;: this.addLocation(); break; case &quot;mark&quot;: this.addMarker(); break; case &quot;MousePosition&quot;: this.addMousePositionControl(); break; case &quot;ScaleLine&quot;: this.addScaleLineControl(); break; case &quot;OverviewMap&quot;: this.addOverviewMapControl(); break; case &quot;mapswitch&quot;: this.addMapSwitch(); break; case &quot;stopDraw&quot;: this.stopDraw(containerDiv); break; default: alert(&quot;没有该工具！&quot;); break; } } } /** * 在地图上添加放大工具 */ addzoomplusTool () { var me = this.map; var div = document.createElement('div'); div.id = &quot;zoomplus&quot;; div.className = 'zoomplus'; div.title = '放大'; this.map.el.dom.appendChild(div); div.onclick = function() { var old_zoom = me._map.getView().getZoom(); var new_zoom = old_zoom + 1; me._map.getView().setZoom(new_zoom); } } /** * 在地图上添加缩小工具 */ addzoomsubTool (){ var me = this.map; var div = document.createElement('div'); div.id = &quot;zoomsub&quot;; div.className = 'zoomsub'; div.title = '缩小'; this.map.el.dom.appendChild(div); div.onclick = function() { var old_zoom = me._map.getView().getZoom(); var new_zoom = old_zoom - 1; me._map.getView().setZoom(new_zoom); } } /** * 在地图上添加初始化View工具 */ addinitViewTool(){ var me = this.map; var init_zoom = me._map.getView().getZoom(); var init_center = me._map.getView().getCenter(); var div = document.createElement('div'); div.id = &quot;initView&quot;; div.className = 'initView'; div.title = '还原'; this.map.el.dom.appendChild(div); div.onclick = function() { me._map.getView().setZoom(init_zoom); me._map.getView().setCenter(init_center); } } /** * 在地图上添加绘制点线面工具 */ adddrawPLPTool(containerDiv){ var me =this.map; var layersArray = this.map.getLayers().getArray(); var measureLayer, measureLayerSource; for(var i=0; i&lt;layersArray.length; i++){ if(layersArray[i].getProperties().id == &quot;measureLayer&quot;){ measureLayer = layersArray[i]; measureLayerSource = measureLayer.getSource(); } } var drawPointDiv = document.createElement('div'); drawPointDiv.id=&quot;drawPoint&quot;; drawPointDiv.className = 'drawPoint'; drawPointDiv.title = '画点'; var drawLineDiv = document.createElement('div'); drawLineDiv.id=&quot;drawLineString&quot;; drawLineDiv.className = 'drawLine'; drawLineDiv.title = '画线'; var drawPolygonDiv = document.createElement('button'); drawPolygonDiv.id=&quot;drawPolygon&quot;; drawPolygonDiv.className = 'drawPolygon'; drawPolygonDiv.innerHTML = '绘制'; // var clearFont = document.createElement('i'); // clearFont.innerHTML = '画面'; // clearFont.className=&quot;iStyle&quot;; // this.map.el.dom.appendChild(drawPointDiv); // this.map.el.dom.appendChild(drawLineDiv); containerDiv.appendChild(drawPolygonDiv) // containerDiv.appendChild(clearFont) this.map.map.a.appendChild(containerDiv); var draw /*drawPointDiv.onclick = function(e){//判断当前点击事件的div名称是哪一个 var Draws = me._map.getInteractions().getArray(); for(var i=Draws.length-1; i&gt;=0; i--){ me._map.removeInteraction(Draws[i]); } if(draw){ me._map.removeInteraction(draw); } draw = new ol.interaction.Draw({ source: measureLayerSource, type: ('Point') }); me._map.addInteraction(draw); } drawLineDiv.onclick = function(e){ var Draws = me._map.getInteractions().getArray(); for(var i=Draws.length-1; i&gt;=0; i--){ me._map.removeInteraction(Draws[i]); } if(draw){ me._map.removeInteraction(draw); } draw = new ol.interaction.Draw({ source: measureLayerSource, type: ('LineString') }); me._map.addInteraction(draw); } drawPolygonDiv.onclick = function(e){ var Draws = me._map.getInteractions().getArray(); for(var i=Draws.length-1; i&gt;=0; i--){ me._map.removeInteraction(Draws[i]); } if(draw){ me._map.removeInteraction(draw); } draw = new ol.interaction.Draw({ source: measureLayerSource, type: ('Polygon') }); me._map.addInteraction(draw); }*/ var _this = this; drawPolygonDiv.onclick = function(e){ _this.map.beginDraw = true; draw = new ol.interaction.Draw({ source: measureLayerSource, type: ('Polygon') }); _this.draw = draw; _this.map.addInteraction(draw); } return containerDiv; } drawPolygonEvent(){ var layersArray = this.map.getLayers().getArray(); var measureLayerSource; for(var i=0; i&lt;layersArray.length; i++){ if(layersArray[i].getProperties().id == &quot;measureLayer&quot;){ var measureLayer = layersArray[i]; measureLayerSource = measureLayer.getSource(); } } this.map.beginDraw = true; var draw = new ol.interaction.Draw({ source: measureLayerSource, type: ('Polygon') }); this.map.draw = draw; this.map.addInteraction(draw); this.getAddFeatures(); return measureLayerSource; } stopDrawEvent(){ this.map.beginDraw = false; this.map.map.removeInteraction(_this.draw); } clearEvent(){ var layersArray = this.map.getLayers().getArray(); var measureLayerSource; for (var i = 0; i &lt; layersArray.length; i++) { if (layersArray[i].getProperties().id == &quot;measureLayer&quot;) { var measureLayer = layersArray[i]; measureLayerSource = measureLayer.getSource(); } } measureLayerSource &amp;&amp; measureLayerSource.clear(); } //停止绘制 stopDraw(containerDiv){ var drawPolygonDiv = document.createElement('button'); drawPolygonDiv.id=&quot;drawPolygon_stop_cap&quot;; drawPolygonDiv.className = 'drawPolygon drawPolygon_stop_cap'; drawPolygonDiv.innerHTML = '停止绘制'; /*var clearFont = document.createElement('i'); clearFont.innerHTML = '停止绘制'; clearFont.className=&quot;iStyle&quot;;*/ //删除绘制的图层装ext按钮 var deletedrawDiv = document.createElement('span'); deletedrawDiv.id = &quot;deletedraw&quot;; deletedrawDiv.className = 'drawPolygon_deleteDraw'; var deletedrawDivFont = document.createElement('button'); deletedrawDivFont.className = 'drawPolygon drawPolygon_stop_cap'; deletedrawDivFont.innerHTML = '删除绘制'; // deletedrawDivFont.className=&quot;iStyle&quot;; containerDiv.appendChild(drawPolygonDiv); // containerDiv.appendChild(clearFont); // containerDiv.appendChild(deletedrawDivFont); containerDiv.appendChild(deletedrawDiv); this.map.map.a.appendChild(containerDiv); // drawPolygonDiv.title = '停止绘制'; //这个方法也可以就是性能不好，创建太多draw // _this.draw.setActive(false); var _this = this; $(drawPolygonDiv).on('click',function(e){ _this.map.beginDraw = false; _this.map.map.removeInteraction(_this.draw); console.log(&quot;aa&quot;); console.log(_this.map.addFeas); }); } //选择要删除的图层 deletePaintedLyrs(lyId){ // appmap.makeSelectable(['earthbolck','road'],true); this.map.makeSelectable([lyId],true); } getAddFeatures(){ var layersArray = this.map.getLayers().getArray(); var measureLayer, measureLayerSource; for(var i=0; i&lt;layersArray.length; i++){ if(layersArray[i].getProperties().id == &quot;measureLayer&quot;){ measureLayer = layersArray[i]; measureLayerSource = measureLayer.getSource(); } } var me = this; measureLayerSource.on('addfeature',function(){ var features = measureLayerSource.getFeatures(); //console.log(features[features.length-1]); me.map.addFeas = features; me.map.measureLayer = measureLayer; }); } saveDK(){ var me = this; var features = me._sourceMa.getFeatures(); console.log(features[features.length-1]); } /** * 在地图上添加测量工具 */ addLineMeasure(){ var me = this; var layersArray = me.map._map.getLayers().getArray(); var measureLayer, measureLayerSource; for (var i = 0; i &lt; layersArray.length; i++) { if (layersArray[i].getProperties().id == &quot;measureLayer&quot;) { measureLayer = layersArray[i]; measureLayerSource = measureLayer.getSource(); } } var measureLineStringdiv = document .createElement('div'); measureLineStringdiv.id = &quot;LineString&quot;; measureLineStringdiv.className = 'measureLineString'; measureLineStringdiv.title = &quot;量距&quot;; me.map.el.dom.appendChild(measureLineStringdiv); var measurePolygondiv = document.createElement('div'); measurePolygondiv.id = &quot;Polygon&quot;; measurePolygondiv.className = 'measurePolygon'; measurePolygondiv.title = &quot;测面&quot;; me.map.el.dom.appendChild(measurePolygondiv); measureTooltipElement = document.createElement('div'); measureTooltipElement.className = 'tooltip tooltip-measure'; measureTooltip = new ol.Overlay({ element : measureTooltipElement, offset : [ 0, -15 ], positioning : 'bottom-center' }); me.map._map.addOverlay(measureTooltip); var draw = new ol.interaction.Draw({ source : measureLayerSource, type : /** @type {ol.geom.GeometryType} */ ('Polygon') }); measureLineStringdiv.onclick = function(e) { var Draws = me.map._map.getInteractions() .getArray(); for (var i = Draws.length - 1; i &gt;= 0; i--) { me.map._map.removeInteraction(Draws[i]); } if (draw) { me.map._map.removeInteraction(draw); } draw = new ol.interaction.Draw({ source : measureLayerSource, type : (measureLineStringdiv.id) }); me.map._map.addInteraction(draw); draw .on( 'drawstart', function(evt) { var output; sketch = evt.feature; var tooltipCoord = evt.coordinate; listener = sketch .getGeometry() .on( 'change', function(evt) { var geom = evt.target; if (geom instanceof ol.geom.Polygon) { output = geom .getArea() + ' ' + 'km&lt;sup&gt;2&lt;/sup&gt;'; tooltipCoord = geom .getInteriorPoint() .getCoordinates(); } else if (geom instanceof ol.geom.LineString) { output = geom .getLength() + ' ' + 'm'; tooltipCoord = geom .getLastCoordinate(); } measureTooltipElement.innerHTML = output; measureTooltip .setPosition(tooltipCoord); }); }, this); draw.on( 'drawend', function(evt) { measureTooltipElement.className = 'tooltip tooltip-static'; measureTooltip.setOffset([ 0, -7 ]); sketch = null; measureTooltipElement = null; me.createMeasureTooltip(); ol.Observable.unByKey(listener); }, this); } measurePolygondiv.onclick = function(e) { var Draws = me.map._map.getInteractions() .getArray(); for (var i = Draws.length - 1; i &gt;= 0; i--) { me.map._map.removeInteraction(Draws[i]); } if (draw) { me.map._map.removeInteraction(draw); } draw = new ol.interaction.Draw({ source : measureLayerSource, type : (measurePolygondiv.id) }); me.map._map.addInteraction(draw); draw .on( 'drawstart', function(evt) { var output; sketch = evt.feature; var tooltipCoord = evt.coordinate; listener = sketch .getGeometry() .on( 'change', function(evt) { var geom = evt.target; if (geom instanceof ol.geom.Polygon) { output = geom .getArea() + ' ' + 'km&lt;sup&gt;2&lt;/sup&gt;'; tooltipCoord = geom .getInteriorPoint() .getCoordinates(); } else if (geom instanceof ol.geom.LineString) { output = geom .getLength() + ' ' + 'm'; tooltipCoord = geom .getLastCoordinate(); } measureTooltipElement.innerHTML = output; measureTooltip .setPosition(tooltipCoord); }); }, this); draw .on( 'drawend', function(evt) { measureTooltipElement.className = 'tooltip tooltip-static'; measureTooltip.setOffset([ 0, -7 ]); sketch = null; measureTooltipElement = null; me.createMeasureTooltip(); ol.Observable.unByKey(listener); }, this); } } /** * 测量时创建输出框 */ createMeasureTooltip() { var me = this.map; if (measureTooltipElement) { measureTooltipElement.parentNode .removeChild(measureTooltipElement); } measureTooltipElement = document.createElement('div'); measureTooltipElement.className = 'tooltip tooltip-measure'; measureTooltip = new ol.Overlay({ element : measureTooltipElement, offset : [ 0, -15 ], positioning : 'bottom-center' }); me._map.addOverlay(measureTooltip); } /** * 在地图上添加测量清除工具 */ addMeasureClear(containerDiv) { var layersArray = this.map.getLayers().getArray(); var measureLayer, measureLayerSource; for (var i = 0; i &lt; layersArray.length; i++) { if (layersArray[i].getProperties().id == &quot;measureLayer&quot;) { measureLayer = layersArray[i]; measureLayerSource = measureLayer.getSource(); } } var markLayer, markLayerSource; for (var i = 0; i &lt; layersArray.length; i++) { if (layersArray[i].getProperties().id == &quot;markLayer&quot;) { markLayer = layersArray[i]; markLayerSource = markLayer.getSource(); } } var cleardiv = document.createElement('button'); // var clearFont = document.createElement('i'); cleardiv.id = &quot;Clear&quot;; cleardiv.className = 'drawPolygon'; cleardiv.innerHTML = '清除'; // clearFont.innerHTML = '清除'; // clearFont.className=&quot;iStyle&quot;; containerDiv.appendChild(cleardiv); // containerDiv.appendChild(clearFont); this.map.map.a.appendChild(containerDiv); var _this = this; cleardiv.onclick = function() { measureLayerSource.clear(); // markLayerSource.clear(); /*var Overlays = me._map.getOverlays().getArray(); for (var i = Overlays.length - 2; i &gt;= 0; i--) { me._map.removeOverlay(Overlays[i]); } var Draws = me._map.getInteractions().getArray(); for (var i = Draws.length - 1; i &gt;= 0; i--) { me._map.removeInteraction(Draws[i]); }*/ } } /** * 在地图上添加定位工具 */ addLocation () { var me = this.map; var locationdiv = document.createElement('div'); locationdiv.id = &quot;Location&quot;; locationdiv.className = 'Location'; locationdiv.title = '定位'; this.map.el.dom.appendChild(locationdiv); var value, center; locationdiv.onclick = function() { // measureLayer.getSource().clear(); this.showWin = Ext .create( 'Ext.window.Window', { width : 300, height : 180, modal : true, name : 'chartWindow', layout : 'fit', shadow : false, title : '输入坐标', items : [ { xtype : 'container', defaults : { margin : '20 10 0 50', labelWidth : 90, width : 250, }, items : [ { xtype : 'textfield', fieldLabel : '经度', name : 'jd', allowBlank : false, margin : '10 10 0 10', }, { xtype : 'textfield', fieldLabel : '纬度', name : 'wd', allowBlank : false, margin : '10 10 0 10', }, { xtype : 'button', cls : 'btn_cus_func', text : '定位', width : 90, labelWidth : 190, textAlign : 'center', handler : function() { var jd = this .up() .down( 'textfield[name=jd]'); var wd = this .up() .down( 'textfield[name=wd]'); var value = []; value[0] = jd .getValue(); value[1] = wd .getValue(); if (value[0] &amp;&amp; value[1]) { center = [ parseFloat(value[0]), parseFloat(value[1]) ]; this .up() .up() .hide(); var layersArray = me._map .getLayers() .getArray(); var markLayer, markLayerSource; for (var i = 0; i &lt; layersArray.length; i++) { if (layersArray[i] .getProperties().id == &quot;markLayer&quot;) { markLayer = layersArray[i]; markLayerSource = markLayer .getSource(); } } var feature = new ol.Feature( { geometry : new ol.geom.Point( center), name : 'My Point' }); var style = new ol.style.Style( { fill : new ol.style.Fill( { color : '#ffff00' }), stroke : new ol.style.Stroke( { color : '#ffff00', width : 1 }), image : new ol.style.Icon( { src : &quot;js/app/frmwk/gis/images/定位.png&quot; }) }); feature .setStyle(style); markLayerSource .addFeature(feature); me._map .getView() .setCenter( center); } else { Ext.Msg .alert( &quot;提示&quot;, &quot;请输入坐标！&quot;); } }, }, { xtype : 'button', cls : 'btn_cus_func', text : '返回', margin : '0 0 0 10', width : 90, textAlign : 'center', handler : function() { this .up() .up() .hide(); } } ] } ] }); this.showWin.show(); }; } /** * 标记地图上某地 */ addMarker(){ var me =this.map; var layersArray = me._map.getLayers().getArray(); var markLayer, markLayerSource; for(var i=0; i&lt;layersArray.length; i++){ if(layersArray[i].getProperties().id == &quot;markLayer&quot;){ markLayer = layersArray[i]; markLayerSource = markLayer.getSource(); } } var markdiv = document.createElement('div'); markdiv.id=&quot;mark&quot;; markdiv.className=&quot;mark&quot;; markdiv.title = '标记'; this.map.el.dom.appendChild(markdiv); var draw; markdiv.onclick = function(e){//判断当前点击事件的div名称是哪一个 var Draws = me._map.getInteractions().getArray(); for(var i=Draws.length-1; i&gt;=0; i--){ me._map.removeInteraction(Draws[i]); } if(draw){ me._map.removeInteraction(draw); } draw = new ol.interaction.Draw({ source: markLayerSource, type: ('Point'), style:new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Icon({ src: 'js/app/frmwk/gis/images/marker.png' }) }) }); me._map.addInteraction(draw); } } /** * 在地图上添加鹰眼组件 */ addOverviewMapControl() { var me = this.map; var OverviewMapControl = new ol.control.OverviewMap({ className : 'ol-zy-overviewmap', collapsed : false, collapseLabel : '\\u00BB', label : '\\u00AB' }); me._map.addControl(OverviewMapControl); } /** * 在地图上添加显示鼠标位置组件 */ addMousePositionControl() { var me =this.map; var textdiv = document.createElement('div'); textdiv.id='mptext'; textdiv.className='ol-mptext'; textdiv.innerHTML = &quot;鼠标位置：&quot; ; var MousePositiondiv = document.createElement('div'); MousePositiondiv.id=&quot;MousePosition&quot;; this.map.el.dom.appendChild(MousePositiondiv); MousePositiondiv.appendChild(textdiv); var MousePositionControl = new ol.control.MousePosition({ className: 'ol-zy-mouse-position', coordinateFormat: ol.coordinate.createStringXY(4), projection: 'EPSG:4326', target: MousePositiondiv }); me._map.addControl(MousePositionControl); } /** * 在地图上添加比例尺组件 */ addScaleLineControl () { var me =this.map; var textdiv = document.createElement('div'); textdiv.id='sltext'; textdiv.className='ol-sltext'; textdiv.innerHTML = &quot;当前比例尺 1:&quot; ; var ScaleLinediv = document.createElement('div'); ScaleLinediv.id=&quot;ScaleLine&quot;; this.map.el.dom.appendChild(ScaleLinediv); ScaleLinediv.appendChild(textdiv); var scaleLineControl = new ol.control.ScaleLine({ className:'ol-zy-scale-line', target: ScaleLinediv, units:'metric' }); me._map.addControl(scaleLineControl); } addMapSwitch(){ var me = this.map; var streetmap, imagemap, reliefmap; var layers = this.map._map.getLayers().getArray(); var streetmap = this.map.getLyrById('amapvec') ? this.map .getLyrById('amapvec') : null; var imagemap = this.map.getLyrById('amapimg') ? this.map .getLyrById('amapimg') : null; // var reliefmap = // this.map.getLyrById('tdtter')?this.map.getLyrById('tdtter'):null; var streetmapdiv = document.createElement('div'); streetmapdiv.id = 'streetmap'; streetmapdiv.className = 'streetmap'; this.map.el.dom.appendChild(streetmapdiv); var imagemapdiv = document.createElement('div'); imagemapdiv.id = 'imagemap'; imagemapdiv.className = 'imagemap'; streetmapdiv.appendChild(imagemapdiv); /* * var reliefmapdiv = document.createElement('div'); * reliefmapdiv.id = 'reliefmap'; reliefmapdiv.className = * 'reliefmap'; streetmapdiv.appendChild(reliefmapdiv); */ streetmapdiv.onmouseover = function() { imagemapdiv.style.display = &quot;block&quot;; // reliefmapdiv.style.display=&quot;block&quot;; }; streetmapdiv.onmouseout = function() { imagemapdiv.style.display = &quot;none&quot;; // reliefmapdiv.style.display=&quot;none&quot;; }; streetmapdiv.onclick = function() { if (streetmap) { streetmap.setVisible(true); } if (imagemap) { imagemap.setVisible(false); } /* * if(reliefmap){ reliefmap.setVisible(false); } */ }; imagemapdiv.onclick = function(e) { e.cancelBubble = true; if (streetmap) { streetmap.setVisible(false); } if (imagemap) { imagemap.setVisible(true); } /* * if(reliefmap){ reliefmap.setVisible(false); } */ }; /* * reliefmapdiv.onclick = function(e){ e.cancelBubble = * true; if(streetmap){ streetmap.setVisible(false); } * if(imagemap){ imagemap.setVisible(false); } * if(reliefmap){ reliefmap.setVisible(true); } }; */ } } export default Tools × Search results Close "},"pointer_TouchSource.js.html":{"id":"pointer_TouchSource.js.html","title":"Source: pointer/TouchSource.js","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Source: pointer/TouchSource.js // Based on https://github.com/Polymer/PointerEvents import EventSource from './EventSource' import MouseSource from './MouseSource' import {arrayRemove} from '../utils/utils' class TouchSource extends EventSource { constructor (dispatcher, mouseSource) { super() let mapping = { 'touchstart': this.touchstart, 'touchmove': this.touchmove, 'touchend': this.touchend, 'touchcancel': this.touchcancel } /** * call */ EventSource.call(this, dispatcher, mapping) /** * @const * @type {!Object.&lt;string, Event|Object&gt;} */ this.pointerMap = dispatcher.pointerMap /** * @const * @type {MouseSource} */ this.mouseSource = mouseSource /** * @private * @type {number|undefined} */ this.firstTouchId_ = undefined /** * @private * @type {number} */ this.clickCount_ = 0 /** * @private * @type {number|undefined} */ this.resetId_ = undefined } /** * Mouse event timeout: This should be long enough to * ignore compat mouse events made by touch. * @const * @type {number} */ static DEDUP_TIMEOUT = 2500 /** * @const * @type {number} */ static CLICK_COUNT_TIMEOUT = 200 /** * @const * @type {string} */ static POINTER_TYPE = 'touch' /** * @private * @param {Touch} inTouch The in touch. * @return {boolean} True, if this is the primary touch. */ isPrimaryTouch_ (inTouch) { return this.firstTouchId_ === inTouch.identifier } /** * Set primary touch if there are no pointers, or the only pointer is the mouse. * @param {Touch} inTouch The in touch. * @private */ setPrimaryTouch_ (inTouch) { let count = Object.keys(this.pointerMap).length if (count === 0 || (count === 1 &amp;&amp; MouseSource.POINTER_ID.toString() in this.pointerMap)) { this.firstTouchId_ = inTouch.identifier this.cancelResetClickCount_() } } /** * @private * @param {Object} inPointer The in pointer object. */ removePrimaryPointer_ (inPointer) { if (inPointer.isPrimary) { this.firstTouchId_ = undefined this.resetClickCount_() } } /** * @private */ resetClickCount_ () { this.resetId_ = setTimeout( this.resetClickCountHandler_.bind(this), TouchSource.CLICK_COUNT_TIMEOUT) } /** * @private */ resetClickCountHandler_ () { this.clickCount_ = 0 this.resetId_ = undefined } /** * @private */ cancelResetClickCount_ () { if (this.resetId_ !== undefined) { clearTimeout(this.resetId_) } } /** * @private * @param {Event} browserEvent Browser event * @param {Touch} inTouch Touch event * @return {Object} A pointer object. */ touchToPointer_ (browserEvent, inTouch) { let e = this.dispatcher.cloneEvent(browserEvent, inTouch) e.pointerId = inTouch.identifier + 2 // TODO: check if this is necessary? e.bubbles = true e.cancelable = true e.detail = this.clickCount_ e.button = 0 e.buttons = 1 e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0 e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0 e.pressure = inTouch.webkitForce || inTouch.force || 0.5 e.isPrimary = this.isPrimaryTouch_(inTouch) e.pointerType = TouchSource.POINTER_TYPE // make sure that the properties that are different for // each `Touch` object are not copied from the BrowserEvent object e.clientX = inTouch.clientX e.clientY = inTouch.clientY e.screenX = inTouch.screenX e.screenY = inTouch.screenY return e } /** * @private * @param {Event} inEvent Touch event * @param {function(Event, Object)} inFunction In function. */ processTouches_ (inEvent, inFunction) { let touches = Array.prototype.slice.call(inEvent.changedTouches) let count = touches.length function preventDefault () { inEvent.preventDefault() } let pointer for (let i = 0; i &lt; count; ++i) { pointer = this.touchToPointer_(inEvent, touches[i]) // forward touch preventDefaults pointer.preventDefault = preventDefault inFunction.call(this, inEvent, pointer) } } /** * @private * @param {TouchList} touchList The touch list. * @param {number} searchId Search identifier. * @return {boolean} True, if the `Touch` with the given id is in the list. */ findTouch_ (touchList, searchId) { let [l, touch] = [touchList.length] for (let i = 0; i &lt; l; i++) { touch = touchList[i] if (touch.identifier === searchId) { return true } } return false } /** * In some instances, a touchstart can happen without a touchend. This * leaves the pointermap in a broken state. * Therefore, on every touchstart, we remove the touches that did not fire a * touchend event. * To keep state globally consistent, we fire a pointercancel for * this &quot;abandoned&quot; touch * @param inEvent * @private */ vacuumTouches_ (inEvent) { let touchList = inEvent.touches let keys = Object.keys(this.pointerMap) let count = keys.length if (count &gt;= touchList.length) { var d = [] var i, key, value for (i = 0; i &lt; count; ++i) { key = keys[i] value = this.pointerMap[key] if (key !== MouseSource.POINTER_ID &amp;&amp; !this.findTouch_(touchList, key - 2)) { d.push(value.out) } } for (i = 0; i &lt; d.length; ++i) { this.cancelOut_(inEvent, d[i]) } } } /** * Handler for `touchstart`, triggers `pointerover`, * `pointerenter` and `pointerdown` events. * @param {Event} inEvent The in event. */ touchstart (inEvent) { this.vacuumTouches_(inEvent) this.setPrimaryTouch_(inEvent.changedTouches[0]) this.dedupSynthMouse_(inEvent) this.clickCount_++ this.processTouches_(inEvent, this.overDown_) } /** * @private * @param {Event} browserEvent The event. * @param {Object} inPointer The in pointer object. */ overDown_ (browserEvent, inPointer) { this.pointerMap[inPointer.pointerId] = { target: inPointer.target, out: inPointer, outTarget: inPointer.target } this.dispatcher.over(inPointer, browserEvent) this.dispatcher.enter(inPointer, browserEvent) this.dispatcher.down(inPointer, browserEvent) } /** * Handler for `touchmove`. * @param {Event} inEvent The in event. */ touchmove (inEvent) { inEvent.preventDefault() this.processTouches_(inEvent, this.moveOverOut_) } /** * @private * @param {Event} browserEvent The event. * @param {Object} inPointer The in pointer. */ moveOverOut_ (browserEvent, inPointer) { let event = inPointer let pointer = this.pointerMap[event.pointerId] // a finger drifted off the screen, ignore it if (!pointer) { return } let outEvent = pointer.out let outTarget = pointer.outTarget this.dispatcher.move(event, browserEvent) if (outEvent &amp;&amp; outTarget !== event.target) { outEvent.relatedTarget = event.target event.relatedTarget = outTarget // recover from retargeting by shadow outEvent.target = outTarget if (event.target) { this.dispatcher.leaveOut(outEvent, browserEvent) this.dispatcher.enterOver(event, browserEvent) } else { // clean up case when finger leaves the screen event.target = outTarget event.relatedTarget = null this.cancelOut_(browserEvent, event) } } pointer.out = event pointer.outTarget = event.target } /** * Handler for `touchend`, triggers `pointerup`, * `pointerout` and `pointerleave` events. * @param {Event} inEvent The event. */ touchend (inEvent) { this.dedupSynthMouse_(inEvent) this.processTouches_(inEvent, this.upOut_) } /** * @private * @param {Event} browserEvent An event. * @param {Object} inPointer The inPointer object. */ upOut_ (browserEvent, inPointer) { this.dispatcher.up(inPointer, browserEvent) this.dispatcher.out(inPointer, browserEvent) this.dispatcher.leave(inPointer, browserEvent) this.cleanUpPointer_(inPointer) } /** * Handler for `touchcancel`, triggers `pointercancel`, * `pointerout` and `pointerleave` events. * @param {Event} inEvent The in event. */ touchcancel (inEvent) { this.processTouches_(inEvent, this.cancelOut_) } /** * @private * @param {Event} browserEvent The event. * @param {Object} inPointer The in pointer. */ cancelOut_ (browserEvent, inPointer) { this.dispatcher.cancel(inPointer, browserEvent) this.dispatcher.out(inPointer, browserEvent) this.dispatcher.leave(inPointer, browserEvent) this.cleanUpPointer_(inPointer) } /** * @private * @param {Object} inPointer The inPointer object. */ cleanUpPointer_ (inPointer) { delete this.pointerMap[inPointer.pointerId] this.removePrimaryPointer_(inPointer) } /** * Prevent synth mouse events from creating pointer events. * * @private * @param {Event} inEvent The in event. */ dedupSynthMouse_ (inEvent) { let lts = this.mouseSource.lastTouches let t = inEvent.changedTouches[0] if (this.isPrimaryTouch_(t)) { let lt = [t.clientX, t.clientY] lts.push(lt) setTimeout(function () { // remove touch after timeout arrayRemove(lts, lt) }, TouchSource.DEDUP_TIMEOUT) } } } export default TouchSource × Search results Close "},"global.html":{"id":"global.html","title":"Global","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Global Members &lt;constant&gt; addClass 添加类名 Source: utils/domUtils.js, line 139 &lt;constant&gt; addListener 对DOM对象添加事件监听 Source: event/Events.js, line 216 &lt;constant&gt; arrayRemove arrayRemove Source: utils/utils.js, line 94 &lt;constant&gt; clear 清空当前对象 Source: event/Events.js, line 180 &lt;constant&gt; create 创建dom Source: utils/domUtils.js, line 70 &lt;constant&gt; createHidden 创建一个隐藏的元素 Source: utils/domUtils.js, line 184 &lt;constant&gt; empty 将dom致空 Source: utils/domUtils.js, line 97 &lt;constant&gt; EventType 事件类型 Source: event/EventType.js, line 5 &lt;constant&gt; findListener 查找监听器 Source: event/Events.js, line 30 &lt;constant&gt; firstUpperToCase 首字母大写(其他小写) Source: utils/utils.js, line 77 &lt;constant&gt; get 通过id获取dom Source: utils/domUtils.js, line 9 &lt;constant&gt; getChildByTagName 获取父节点下指定的子节点 Source: utils/domUtils.js, line 19 &lt;constant&gt; getClass 获取dom class Source: utils/domUtils.js, line 43 &lt;constant&gt; getDomEventKey 获取事件唯一标识 Source: event/Events.js, line 204 &lt;constant&gt; getElementsByClassName 通过类名获取元素 Source: utils/domUtils.js, line 30 &lt;constant&gt; getListeners get Listeners Source: event/Events.js, line 50 &lt;constant&gt; getrandom 获取两数值之间的随机值 Source: utils/utils.js, line 10 &lt;constant&gt; getStyle 获取dom样式列表（） Source: utils/domUtils.js, line 53 &lt;constant&gt; getuuid 获取id Source: utils/utils.js, line 30 &lt;constant&gt; hasClass 判断DOM对象是否有此类名 Source: utils/domUtils.js, line 126 &lt;constant&gt; isObject 判断是否为对象 Source: utils/utils.js, line 108 &lt;constant&gt; isString 判断是否为字符串 Source: utils/utils.js, line 118 &lt;constant&gt; layerConfigDefautls 图层默认配置项 Source: constants.js, line 26 &lt;constant&gt; listen 注册事件处理 Source: event/Events.js, line 101 &lt;constant&gt; listenOnce 注册事件，只触发一次 Source: event/Events.js, line 134 &lt;constant&gt; logo :string logo Type: string Source: asset/base64.js, line 9 &lt;constant&gt; OL_Style_Type ol 的常用style类型 Source: constants.js, line 78 &lt;constant&gt; remove 移除当前dom Source: utils/domUtils.js, line 86 &lt;constant&gt; removeClass 移除类名 Source: utils/domUtils.js, line 156 &lt;constant&gt; removeListener 移除DOM对象监听事件 Source: event/Events.js, line 242 &lt;constant&gt; removeListeners 清空事件 Source: event/Events.js, line 74 &lt;constant&gt; setClass 设置class Source: utils/domUtils.js, line 169 &lt;constant&gt; splitWords 将类名截取成数组 Source: utils/utils.js, line 68 &lt;constant&gt; stamp 添加标识 Source: utils/utils.js, line 48 &lt;constant&gt; toBack 添加到容器后放 Source: utils/domUtils.js, line 115 &lt;constant&gt; toFront 添加到容器前方 Source: utils/domUtils.js, line 107 &lt;constant&gt; trim 去除字符串前后空格 Source: utils/utils.js, line 59 &lt;constant&gt; unListen 取消事件注册 Source: event/Events.js, line 145 &lt;constant&gt; unlistenAll 移除所有事件监听 Source: event/Events.js, line 190 &lt;constant&gt; unListenByKey 根据事件名移除事件对象 Source: event/Events.js, line 159 &lt;constant&gt; upperFirstChart 只转换第一个字母 Source: utils/utils.js, line 84 × Search results Close "},"classes.list.html":{"id":"classes.list.html","title":"Classes","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Classes Classes Base Event Html Internal Popup × Search results Close "},"index.html":{"id":"index.html","title":"Index","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart GMap项目介绍{以下是码云平台说明，您可以替换为您的项目简介码云是开源中国推出的基于 Git 的代码托管平台（同时支持 SVN）。专为开发者提供稳定、高效、安全的云端软件开发协作平台无论是个人、团队、或是企业，都能够用码云实现代码托管、项目管理、协作开发。企业项目请看 https://gitee.com/enterprises} 软件架构软件架构说明 安装教程 xxxx xxxx xxxx 使用说明 xxxx xxxx xxxx 参与贡献 Fork 本项目 新建 Feat_xxx 分支 提交代码 新建 Pull Request 码云特技 使用 Readme_XXX.md 来支持不同的语言，例如 Readme_en.md, Readme_zh.md 码云官方博客 blog.gitee.com 你可以 https://gitee.com/explore 这个地址来了解码云上的优秀开源项目 GVP 全称是码云最有价值开源项目，是码云综合评定出的优秀开源项目 码云官方提供的使用手册 http://git.mydoc.io/ 码云封面人物是一档用来展示码云会员风采的栏目 https://gitee.com/gitee-stars/ × Search results Close "},"Base.html":{"id":"Base.html","title":"Class: Base","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Class: Base Base new Base() Source: map/ContextMenu.js, line 715 Extends ol.control.Control × Search results Close "},"Event.html":{"id":"Event.html","title":"Class: Event","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Class: Event Event Created by FDD on 2017/8/8. new Event() Source: event/Event.js, line 4 Members preventDefault preventDefault Source: event/Event.js, line 57 propagationStopped :boolean Type: boolean Source: event/Event.js, line 9 stopPropagation stopPropagation Source: event/Event.js, line 49 target :Object The event target. Type: Object Source: event/Event.js, line 23 type :string The event type. Type: string Source: event/Event.js, line 16 Methods preventDefault() Stop event propagation. Source: event/Event.js, line 31 stopPropagation() Stop event propagation. Source: event/Event.js, line 41 × Search results Close "},"Html.html":{"id":"Html.html","title":"Class: Html","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Class: Html Html new Html() Source: map/ContextMenu.js, line 579 × Search results Close "},"Internal.html":{"id":"Internal.html","title":"Class: Internal","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Class: Internal Internal new Internal() Source: map/ContextMenu.js, line 362 × Search results Close "},"ol.Overlay.Popup.html":{"id":"ol.Overlay.Popup.html","title":"Class: Popup","body":" Common Modules Classes BaseEventHtmlInternalol.Overlay.Popup Global addClassaddListenerarrayRemoveclearcreatecreateHiddenemptyEventTypefindListenerfirstUpperToCasegetgetChildByTagNamegetClassgetDomEventKeygetElementsByClassNamegetListenersgetrandomgetStylegetuuidhasClassisObjectisStringlayerConfigDefautlslistenlistenOncelogoOL_Style_TyperemoveremoveClassremoveListenerremoveListenerssetClasssplitWordsstamptoBacktoFronttrimunListenunlistenAllunListenByKeyupperFirstChart Class: Popup Popup A popup element to be displayed over the map and attached to a single maplocation. Like ol.control.Control, Overlays are visible widgets.Unlike Controls, they are not in a fixed position on the screen, but are tiedto a geographical coordinate, so panning the map will move an Overlay but nota Control. Example: var popup = new ol.Overlay.Popup(); map.addOverlay(popup); popup.show(coordinate, &quot;Hello!&quot;); popup.hide(); new Popup(options) Parameters: Name Type Description options olx.OverlayOptions Overlay options + popupClass: the a class for the overlay. + closeBox: popup has a close box. + onclose: callback when popup is closed + onshow: callback when popup is shown + positionning: add 'auto' to let the popup choose a good positioning. Source: overlay/popupoverlay.js, line 30 Extends ol.Overlay Methods addPopupClass(class) Add a CSS class to the popup. Parameters: Name Type Description class string name. Source: overlay/popupoverlay.js, line 128 getVisible() → {boolean} Check if popup is visible Source: overlay/popupoverlay.js, line 168 Returns: Type boolean hide() Hide the popup Source: overlay/popupoverlay.js, line 229 removePopupClass(class) Remove a CSS class to the popup. Parameters: Name Type Description class string name. Source: overlay/popupoverlay.js, line 137 setClosebox(class) Set CSS class of the popup. Parameters: Name Type Description class string name. Source: overlay/popupoverlay.js, line 93 setPopupClass(class) Set the CSS class of the popup. Parameters: Name Type Description class string name. Source: overlay/popupoverlay.js, line 118 setPositioning(class) Remove a CSS class to the popup. Parameters: Name Type Description class string name. Source: overlay/popupoverlay.js, line 146 setTitle() 设置标题 Source: overlay/popupoverlay.js, line 102 show(the, the) Set the position and the content of the popup. Parameters: Name Type Description the ol.Coordinate | string coordinate of the popup or the HTML content. the string | undefined HTML content (undefined = previous content). Source: overlay/popupoverlay.js, line 178 × Search results Close "}}
    </script>

    <script type="text/javascript">
        $(document).ready(function() {
            Searcher.init();
        });

        $(window).on("message", function(msg) {
            var msgData = msg.originalEvent.data;

            if (msgData.msgid != "docstrap.quicksearch.start") {
                return;
            }

            var results = Searcher.search(msgData.searchTerms);

            window.parent.postMessage({"results": results, "msgid": "docstrap.quicksearch.done"}, "*");
        });
    </script>
</body>
</html>
